[LeetCode] 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.

 

Hide Tags
 Math Bit Manipulation
 
 
分析:
方法一:可以统计n中含有1 的个数,如果只有一个1,那么是
 
方法二:判断n & (n-1) 是否为0.
 
class Solution {
    public:
        bool isPowerOfTwo(int n) {
            if(n <= 0)
                return false;
            if ((n & (n-1)) == 0)
                return true;
            else
                return false;
        }   
};

 

 
posted @ 2015-07-06 14:43  穆穆兔兔  阅读(183)  评论(0编辑  收藏  举报