Given an integer, write a function to determine if it is a power of two.
思路:
2的power二进制都是最高位为1低位全0。所以n 与 n-1相与操作后应该是0
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && ((n & (n - 1)) == 0);
}
};
Given an integer, write a function to determine if it is a power of two.
思路:
2的power二进制都是最高位为1低位全0。所以n 与 n-1相与操作后应该是0
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && ((n & (n - 1)) == 0);
}
};