Doubling Capacity Check
EasyBit Manipulation
Problem
A storage pool can only be provisioned in sizes that come from doubling a single unit block: 1, 2, 4, 8, and so on. Given a requested size size, decide whether it is a valid pool size.
Return true if size is a power of two (2^k for some integer k ≥ 0), otherwise false. Zero and negative sizes are never valid.
Example 1
- Input:
- size = 16
- Output:
- true
16 = 2^4.
Example 2
- Input:
- size = 6
- Output:
- false
6 is 110 in binary: two bits are set.
Example 3
- Input:
- size = 1
- Output:
- true
1 = 2^0.
Constraints
- -2^31 ≤ size < 2^31
- Solve it without loops or recursion.
Hint
Show the first hint
What does a power of two look like in binary?
Walkthrough
How to approach it
01Clarify before coding
- Is 1 valid? Yes, it is 2^0.
- Are negative inputs possible? Yes; they are never valid, and in 32-bit two's complement -2^31 has a single set bit, so it must be excluded by the sign check, not by the bit trick.
02Brute force
While size is even and positive, divide by 2; it is a power of two if you end at 1.
Cost: O(log size) time, O(1) space. Fine in practice, but the follow-up asks for a constant-time, loop-free test.
The rest of the walkthrough is in the app
The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.
This problem is part of Pro.