Power of Two
Easy bit-manipulation · math
Description
Constraints
n is any integer
Examples
Input: n = 16
Output: true
Hints (1)
- A positive power of two has exactly one set bit, so n & (n - 1) is zero.
Solutions
Single set-bit test. · Time O(1) · Space O(1)
func isPowerOfTwo(n int) bool {
return n > 0 && n&(n-1) == 0
}
Single set-bit test. · Time O(1) · Space O(1)
function isPowerOfTwo(n) {
return n > 0 && (n & (n - 1)) === 0;
}
Single set-bit test. · Time O(1) · Space O(1)
function isPowerOfTwo($n) {
return $n > 0 && ($n & ($n - 1)) === 0;
}
Single set-bit test. · Time O(1) · Space O(1)
def isPowerOfTwo(n):
return n > 0 and (n & (n - 1)) == 0
Single set-bit test. · Time O(1) · Space O(1)
function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
Create a free account to submit solutions, track progress and save problems.
Create account