You get an integer n. Decide whether n equals 4 raised to some whole-number power x ≥ 0: answer true if so and false if not.
So 1, 4, 16, 64 and so on are powers of four. Zero and negative numbers never are.
Example 1
Input: n = 256 Output: true Why: 256 = 4 · 4 · 4 · 4
2 more examples and the constraints
Example 2
Input: n = 32 Output: false Why: 32 is 2⁵, an odd power of two
Example 3
Input: n = 1 Output: true Why: 4⁰ = 1
Constraints
- −2,147,483,648 ≤ n ≤ 2,147,483,647 (any 32-bit 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.
- Divide by 4O(log n)
- One bit, even placeO(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 |
|---|---|---|---|
| Divide by 4 | O(log n) | Passes; uses a loop | |
| One bit, even place | O(1) | Best; answers the follow-up |
n = the number being tested.
Edge cases to test
- n = 1. 4⁰ = 1, so true. Its one bit is at position 0, which is even.
- n = 0. False. Without the sign check,
0 % 4 == 0keeps the loop running forever. - Odd powers of two. 2, 8, 32 have one set bit, but at an odd position: false.
- Negative numbers. −4 is never 4 to a power. The smallest int has one set bit (the sign bit), so the n > 0 check is needed.
Common mistakes
- Stopping at the power-of-two test, so 2, 8 and 32 come back true.
- Leaving out n > 0, so 0 passes
n & (n - 1) == 0and the smallest int looks like one bit. - Using the mask 0xAAAAAAAA, which marks the odd positions, the wrong ones.
How to talk through it
- 1Clarify. Is 1 a power of four? What should 0 and negative numbers return?
- 2Give the loop. Divide by 4 while it goes in evenly and check that 1 is left; O(log n).
- 3Look at the bits. Write 1, 4, 16, 64 in binary: one 1, always at an even position.
- 4Code the checks. Positive,
n & (n - 1) == 0, andn & 0x55555555 != 0; say what each one rules out. - 5Test out loud. Run 1, 0, 2, 32 and 256 through the three checks.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?