class Solution { public boolean isPowerOfTwo(int n) { return n > 0 && n - (n & -n) == 0; } }
有点不明白。如果我写成
class Solution { public: bool isPowerOfTwo(int n) { if(n == 0) return false; return ( n == (n&-n) ); } };
会提示出错。 Line 6: Char 26: runtime error: negation of -2147483648 cannot be represented in type ‘int’; cast to an unsigned type to negate this value to itself (solution.cpp) 求大佬解释。。
负数和0肯定不符题意,所以if (n <= 0) return false
0
if (n <= 0) return false
谢谢!我明白了。
有点不明白。如果我写成
会提示出错。
Line 6: Char 26: runtime error: negation of -2147483648 cannot be represented in type ‘int’; cast to an unsigned type to negate this value to itself (solution.cpp)
求大佬解释。。
负数和
0
肯定不符题意,所以if (n <= 0) return false
谢谢!我明白了。