
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)
1function hasAlternatingBits(n) {
2 let xor = n ^ (n >> 1);
3 return (xor & (xor + 1)) === 0;
4}This solution makes use of JavaScript's bitwise operations. By XORing n with its right shift and check if the XOR-ed value and the XOR-ed value plus one equate to zero, we can assert the alternating nature.
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)
1
bool hasAlternatingBits(int n) {
while(n > 0) {
int last = n % 2;
n = n >> 1;
if(last == (n % 2)) return false;
}
return true;
}The solution uses a loop to check paired bits from right to left, comparing them to determine if they are alternating.