231 - power of two

Given an integer, write a function to determine if it is a power of two.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

bool isPowerOfTwo(int n) {
    int cnt = 0;
        while (n > 0) {
            /* 計算最低位1的個數 */
            cnt += (n & 1);
            n >>= 1;
        }
    return cnt == 1;
}

起初理解錯了題目,算成了是否是2的倍數,其實是power,這樣就簡單多了。

也可以這樣:

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return (n > 0) && (!(n & (n - 1)));
    } 
};


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