⚡ TL;DR
Check power of two in Python with working code. Bit manipulation approach with O(1) time, plus complexity analysis and interview tips.
Power of Two (#231 — Easy): Given an integer n, return true if it is a power of two. Otherwise, return false.
Problem Statement
Given an integer n, return true if it is a power of two. Otherwise, return false.
Example:
Input: n = 16
Output: true
Explanation: 16 = 2⁴, so it is a power of two.Approach: Bit Mask Trick
Time: O(1) | Space: O(1)
A power of two has exactly one set bit: 1, 10, 100, 1000… Subtracting 1 flips that bit and sets every bit below it, so n & (n−1) is zero only for powers of two — guarded by n > 0.
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
for v in (1, 16, 18, 0):
print(v, "->", "true" if is_power_of_two(v) else "false")Approach: Repeated Division
Time: O(log n) | Space: O(1)
Divide by 2 while the value is even; a true power of two collapses all the way to 1. Simple to reason about and a good baseline before reaching for the bit trick.
def is_power_of_two_divide(n):
if n <= 0:
return False
while n % 2 == 0:
n //= 2
return n == 1
for v in (1, 16, 18, 0):
print(v, "->", "true" if is_power_of_two_divide(v) else "false")Key Takeaways
- n & (n−1) == 0 is the one-line signature of a power of two
- The n > 0 guard matters: 0 and negatives pass the bit check but are not powers of two
- Repeated division is the readable fallback when bit tricks feel opaque
FAQ
What is the best approach to solve Power of Two in Python?
The recommended approach is Bit Mask Trick, which runs in O(1) time with O(1) space. The full Python implementation is shown above.
What is the time complexity of Power of Two in Python?
Using Bit Mask Trick, the time complexity is O(1) and the space complexity is O(1); Repeated Division runs in O(log n) time with O(1) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →