
Sponsored
Sponsored
In this approach, we will use bitwise operations to compare each bit with its adjacent one. The key is to repeatedly XOR the number with itself shifted one position to the right, which will result in a number with all bits set to 1 if the original number has alternating bits. Such a number should satisfy (n & (n + 1)) == 0.
Time Complexity: O(1), Space Complexity: O(1)
1class Solution:
2 def hasAlternatingBits(self, n: int) -> bool:
3 xor = n ^ (n >> 1)
4 return (xor & (xor + 1)) == 0The solution leverages Python's bitwise operations to determine if a number’s binary representation has alternating bits by exploiting the XOR between the number and its shifted version.
This approach involves checking each bit pair iteratively. We will repeatedly check if the last two bits are the same or different by analyzing the least significant bits and shifting the number to the right iteratively.
Time Complexity: O(log N), where N is the value of the number. Space Complexity: O(1)
1The Python solution checks bits iteratively, each time reducing the number by shifting right and comparing the least significant bit.