LeetCode之Power of Two

/*方法一:用2除。*/
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n < 1) return false;
        while(n != 1){
            if((n & 1) != 0) return false;
            n /= 2;
        }
        return true;
    }
};

/*方法二:如果n爲2的次冪的數,則二進制表示的n中。
1的個數爲1,所以可以採用位操作。*/
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        int count = 0;
        for(int i = 0; i < 32; ++i){
            if(((n >> i) & 1) == 1) ++count;
        } 
        return count == 1;
    }
};

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