
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)
1#include <iostream>
2
3bool hasAlternatingBits(int n) {
4 int xor_result = n ^ (n >> 1);
5 return (xor_result & (xor_result + 1)) == 0;
6}Using XOR operation and shifting the number, it checks for the condition that results in all 1s for alternating bits. The condition is simple: (xor_result & (xor_result + 1)) == 0.
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
This implementation analyzes the last two bits of the number by checking the modulus and right-shifting iteratively. It ensures they are different, ensuring the bits alternate.