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
Tested onlyTime 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
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?