#693
Binary Number with Alternating Bits
EasyBit ManipulationBit ManipulationGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages bit manipulation to check for alternating bits without converting to a binary string. This is more efficient as it directly uses the properties of binary numbers.
⚙️
Algorithm
3 steps- 1Step 1: Create a variable 'prev' initialized to -1 to store the previous bit.
- 2Step 2: Use a loop to right-shift the number until it becomes 0.
- 3Step 3: In each iteration, check if the last bit (n & 1) is the same as 'prev'. If yes, return false; otherwise, update 'prev' and right-shift n.
solution.py11 lines
1# Full working Python code
2
3def hasAlternatingBits(n):
4 prev = -1
5 while n > 0:
6 current = n & 1 # Get the last bit
7 if current == prev:
8 return False
9 prev = current
10 n >>= 1 # Right shift n
11 return Trueℹ
Complexity note: The time complexity is O(n) because we process each bit of the number once. The space complexity is O(1) as we are only using a fixed amount of extra space.
- 1Bit manipulation can simplify the problem significantly.
- 2Understanding binary representation helps in optimizing solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.