leetcode231 2的幂 leetcode342 4的幂 leetcode326 3的幂
1.2的幂
正确写法:
class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; return (n & (n-1)) == 0; } };
错误写法1:
&符号的短路原则,如果&前面为false了就不会计算后面的了
class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; retur
class Solution { public: bool isPowerOfFour(int num) { if(num <= 0) return false; if((num & (num - 1)) == 0){ if(num & 0x55555555) return true; else return false; } else return false; } };
n ((n-1) & n) == 0; } };
错误写法2
==符号的优先级比&高
class Solution { public: bool isPowerOfTwo(int n) { if(n <= 0) return false; return n & (n-1) == 0; } };
2.4的幂
class Solution { public: bool isPowerOfFour(int num) { if(num <= 0) return false; if((num & (num - 1)) == 0){ if(num & 0x55555555) return true; else return false; } else return false; } };
3.3的幂
https://blog.csdn.net/u014218090/article/details/80152446