Check if a Number is Power of 2
Implement isPowerOfTwo
Given an integer
n, determine whether it's a power of 2 (1, 2, 4, 8, 16, ...). Zero and negative numbers are never powers of 2.
Repeatedly dividing by 2 until an odd remainder or 1 shows up works, but a power of 2 has a distinctive binary shape: exactly one bit set, with every bit below it clear. Subtracting 1 from such a number flips that single bit off and every lower bit on — a pattern that never overlaps with the original number, so n & (n - 1) collapses straight to 0 only when n had exactly one bit set to begin with.
Example 1:
Input: n = 1
Output: true
Example 2:
Input: n = 16
Output: true
Example 3:
Input: n = 3
Output: false
+ 9 hidden test cases run on Submit.
Constraints:
- ●
-2³¹ ≤ n ≤ 2³¹ − 1
n =
1