【Leetcode Algorithm】Power of Two

Given an integer, write a function to determine if it is a power of two.
第一次嘗試代碼:
public class Solution {
    public boolean isPowerOfTwo(int n) {
        //如果爲0,則false
        if(n==0){
            return false;
        }
        //2^0=1
        if(n==1){
            return true;
        }
        //n爲奇數則肯定不是,若是偶數則遞歸解決
        if(n%2!=0){
            return false;
        }
        else{
            Solution s = new Solution();
            return s.isPowerOfTwo(n/2);
        }
    }
}


第二次嘗試代碼:
public class Solution {
    public boolean isPowerOfTwo(int n) {
        //負數與0都不是
        if(n<=0){
            return false;
        }
        //如果n與n-1與運算之後不爲0,則表明n的二進制數1的個數大於1,則判定肯定不是
        else if((n&(n-1))!=0){
            return false;
        }
        else{
            return true;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章