Power of Two Check
Mediumjava
Read a positive integer and decide whether it is a power of two (1, 2, 4, 8, 16, ...), using the trick (n & (n - 1)) == 0.
Input: one integer n (n >= 1).
Output: one line — Yes or No.
Example 1
Input
8
Output
Yes
Example 2
Input
6
Output
No
- 1 <= n <= 1000000000
Hint 1
A power of two has exactly one bit set; n - 1 flips that bit and all below it.
Hint 2
Keep the parentheses: (n & (n - 1)) == 0, because == binds tighter than &.
For a power of two, the binary form is a single 1 bit. Subtracting 1 turns that bit to 0 and all lower bits to 1, so ANDing the two gives 0. Any other number shares at least one bit with n - 1.