Is it a power of two
A page allocator only caps sizes at exact powers of two, and a build report flags a size that slipped through.
- Only non-negative sizes make sense here; anything negative is not a power of two.
- Zero is not a power of two.
- One counts: it is two raised to the zeroth power.
isPowerOfTwo(amount: int) → bool
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
bool isPowerOfTwo(int amount) {
}
Worked examples
| Call | Result |
|---|---|
isPowerOfTwo(1) | true |
isPowerOfTwo(2) | true |
isPowerOfTwo(4) | true |
isPowerOfTwo(6) | false |
Hint
A power of two has exactly one bit set. Clearing the lowest set bit with n & (n - 1) turns it to zero.
Reference solution in C++
bool isPowerOfTwo(int amount) {
return amount > 0 && (amount & (amount - 1)) == 0;
}