Problem Description
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5 Output: true Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7 Output: false Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11 Output: false Explanation: The binary representation of 11 is: 1011.
Solution Code
class Solution {
public:
bool hasAlternatingBits(int n) {
int org = n;
vector arr;
while(org){
arr.push_back(org & 1);
org >>= 1;
}
bool flag = true;
for(int i = 1 ; i < arr.size() ; i++){
if((arr[i] ^ arr[i-1]) == 0) flag = false;
}
return flag;
}
};
Solution Explanation
The problem involves determining if a number's binary representation has alternating bits. The solution follows these steps:
- Extract Bits: Convert the integer to its binary representation by extracting each bit.
- Check Alternation: Verify if each bit alternates from the previous bit. If any adjacent bits are the same, return false.
- Return Result: If all bits alternate correctly, return true; otherwise, return false.