You are given a whole number n. Decide whether it equals 2 raised to some whole power k ≥ 0, that is one of 1, 2, 4, 8, 16 and so on.
Return true if it does and false otherwise. Zero and negative numbers are never powers of two.
Example 1
Input: n = 64 Output: true Why: 64 = 2 × 2 × 2 × 2 × 2 × 2
2 more examples and the constraints
Example 2
Input: n = 12 Output: false Why: 12 = 4 × 3, and 3 is odd
Example 3
Input: n = -16 Output: false Why: a power of two is always positive
Constraints
- −2,147,483,648 ≤ n ≤ 2,147,483,647 (any 32-bit signed integer)
- Follow-up: answer without a loop or recursion
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Keep halvingO(log n)
- Count the set bitsO(1)
- n & (n − 1)O(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 1,073,741,824 | Verdict |
|---|---|---|---|
| Keep halving | O(log n) | Passes; uses a loop | |
| Count the set bits | O(1) | Passes; needs a built-in | |
| n & (n − 1) | O(1) | Best; one expression |
n = the input number; log n is at most 31 here.
Edge cases to test
- Zero. 0 & (0 − 1) is 0, so without the
n > 0check, 0 would pass. - One. 1 is 2 to the power 0, so it must return true.
- Negative numbers. -16 and the smallest int, -2,147,483,648, are both false.
- Largest power that fits. 1,073,741,824 (2 to the 30) is true; 2,147,483,647 is not.
Common mistakes
- Dropping the
n > 0check, so 0 and the smallest int come back true. - Writing
n & n - 1 == 0in Java, C++ or TypeScript:==binds tighter than&, so the parentheses are needed. - Testing whether
log2(n)is a whole number in floating point, which can round wrong near large powers.
How to talk through it
- 1Clarify. Can n be zero or negative? Is 1 a power of two? (Yes: 2 to the 0.)
- 2Start with halving. Divide by 2 while even and check for 1; say it is O(log n), at most 31 steps.
- 3Think in binary. A power of two is a single 1 bit followed by 0s.
- 4Use the bit trick. n & (n − 1) clears the lowest set bit; zero left means there was only one.
- 5Test out loud. Run 0, 1, a negative number and 2 to the 30 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?