Power of Two
Given an integer n, return true if it is a power of two . Otherwise, return false. A power of two has exactly one set bit , so n & (n - 1) — the trick that clears the lowest set bit — leaves 0 only when n was a power of two.
Constraints
- -231 ≤ n ≤ 231 - 1
Example
n = 16trueExplanation 16 = 24, and its binary form 10000 has exactly one set bit.
In plain terms
- Power of two
- A number of the form 2^x for some non-negative integer x — 1, 2, 4, 8, 16, and so on.
Clear the lowest set bit and check what remains
n = 16 = 10000. n - 1 = 15 = 01111.
What happens in this step
n = 16, n - 1 = 15 n = 00010000 n - 1 = 00001111 16 has a single set bit at position 4. Subtracting 1 flips that bit off and sets every bit below it to 1, so n - 1 shares none of n's bits — a promising sign for a power of two.
Steps to visualize
- If n is 0 or negative, it cannot be a power of two — return false immediately.
- Compute n & (n - 1), which clears the lowest set bit.
- If n had exactly one set bit, this leaves 0.
- If any bits remain, n had more than one set bit and is not a power of two.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
n = 16 = 10000. n - 1 = 15 = 01111.
What happens in this step
n = 16, n - 1 = 15 n = 00010000 n - 1 = 00001111 16 has a single set bit at position 4. Subtracting 1 flips that bit off and sets every bit below it to 1, so n - 1 shares none of n's bits — a promising sign for a power of two.
Solution
function isPowerOfTwo(n) {
if (n <= 0) {
return false;
}
return (n & (n - 1)) === 0;
}- Time
- O(1)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
n = 16 | true | example from the docstring |
n = 1 | true | 2^0 is a power of two |
n = 0 | false | zero has no set bits and is not a power of two |
n = -16 | false | a negative value can never be a power of two |
n = 218 | false | a value with more than one set bit |
n = 1073741824 | true | a large power of two near the 32-bit boundary |
n = 3 | false | two adjacent set bits |