[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;
        }   
};
 
原文地址:https://www.cnblogs.com/diegodu/p/4624342.html