easyBit ManipulationPure DSA~10 min
Capacity Power Of Two
A ring buffer requires its capacity to be an exact power of two so that index wrapping can use a cheap bit-mask instead of a modulo. Validate a requested capacity.
Problem
Given an integer n, return true if n is a power of two (n = 2^k for some integer k ≥ 0), otherwise false.
Input
A single integer n (-2^31 ≤ n ≤ 2^31 - 1).
Output
A boolean — true if n is a power of two.
Constraints
- n may be zero or negative (both are not powers of two)
- Aim for O(1) without a loop if possible
- Use 32-bit-safe operations
Examples
Example 1
Input
n = 16
Output
true
16 = 2^4.
Example 2
Input
n = 3
Output
false
3 is not any power of two.