Easybit-manipulation
Power of Two
Problem (restated)
Return true if n is a power of two (positive integer with exactly one bit set).
Intuition
Powers of two are 1,2,4,8… Clearing the lowest set bit of such n yields 0: n & (n-1) == 0, and n > 0.
Approaches
n & (n-1) == 0
UnverifiedTime O(1)Space O(1)
Idea. Reject non-positive. One-liner bit trick.
Walkthrough. 16 → true; 3 → false; 0 → false.
Trade-offs. Log loop also works; bit check is O(1).
Solution
export function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
export function isPowerOfTwo(n: number): boolean {
return n > 0 && (n & (n - 1)) === 0;
}
Template connection
Bit tricks: lowest-set-bit clear.
Reflection
- A power of two is positive and has one bit set:
n > 0andn & (n - 1) == 0. - 0 and every negative are false. 1 is true, because it is
2**0. - Two bits set means
n - 1does not clear both of them, so the AND is not 0.