#231

Power of Two

Easy
MathBit ManipulationRecursionBit ManipulationMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(log n)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

A more efficient way to check if a number is a power of two is to use bit manipulation. A power of two has exactly one bit set in its binary representation.

⚙️

Algorithm

2 steps
  1. 1Step 1: If n is less than or equal to 0, return false.
  2. 2Step 2: Check if n & (n - 1) equals 0. This checks if there is only one bit set in n.
solution.py4 lines
1# Full working Python code
2
3def isPowerOfTwo(n):
4    return n > 0 and (n & (n - 1)) == 0

Complexity note: The time complexity is O(1) because we are performing a constant-time bitwise operation. The space complexity is O(1) as well since we are using a constant amount of space.

  • 1A power of two has exactly one bit set in its binary representation.
  • 2Using bit manipulation can significantly reduce the time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.