Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two if there exists an integer x such that n == 2^x.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two if there exists an integer x such that n == 2^x.
An easy math problem, graded against 8 test cases (5 of them hidden).
Number theory, digit manipulation, and closed-form reasoning.
Reach for it when you see: Primes, digits, base conversion, or a problem with a formula hiding behind it.
More Math problems →A power of two in binary representation has exactly one bit set to 1 (e.g., 1 = 1, 2 = 10, 4 = 100, 8 = 1000).
The trick: `n & (n - 1)` removes the lowest set bit. For a power of two, this results in 0. Combined with the check that `n > 0`, this gives us an O(1) solution.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.