[Leetcode 693] Binary Number with Alternating Bits

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010.
Input: n = 3
Output: false
bool hasAlternatingBits(int n){
int prev = n&1;
n = n >> 1;

while(n){
if(prev == (n&1)){
return false;
}

prev = n & 1;
n = n >> 1;
}
return true;
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store