231. Power of Two
Problem
Decide whether the integer n is a power of two (2ˣ for some integer x ≥ 0).
Example: 16 → true; 3 → false; 1 → true
Constraints: follow-up: without loops or recursion.
A power of two has exactly one set bit: n > 0 and n & (n − 1) == 0.
Complexity: O(1).
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and n & (n - 1) == 0
assert Solution().isPowerOfTwo(16) is True
assert Solution().isPowerOfTwo(3) is False
assert Solution().isPowerOfTwo(-16) is False
class Solution {
public boolean isPowerOfTwo(int n) { return n > 0 && (n & (n - 1)) == 0; }
}
func isPowerOfTwo(n int) bool {
return n > 0 && n&(n-1) == 0 // exactly one bit set
}