题目
提示:
-231 <= n <= 231 - 1
进阶:你能够不使用循环/递归解决此问题吗?
题解
n & (n−1),其运算结果恰为把n 的二进制位中的最低位的 1 变为 0之后的结果。
要考虑n大于0
代码
// class Solution {
// public:
// bool isPowerOfTwo(int n) {
// if(n<=0)
// return false;
// if((n&(n-1))==0)
// return true;
// return false;
// }
// };
// class Solution {
// public:
// bool isPowerOfTwo(int n) {
// return n > 0 && (n & (n - 1)) == 0;// n > 0 && (n & (-n)) == n;
// }
// };
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (-n)) == n;
}
};