Given an integer, write a function to determine if it is a power of two.
C Solution 1:
bool isPowerOfTwo(int n) {
if (n <= 0) return false;
for (; !(n & 1); n >>= 1);
return !(n >> 1);
}
C Solution 2:
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
Summary:
- bit manipulation.
- find the first set bit, then right-shift this bit, check if the value is zero or not.
- 6ms, 0%
LeetCode: 231. Power of Two





近期评论