Binary Number with Alternating Bits
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
Let the input number n is A31 A30 ..... A0.
Check the adjacent bits which are Ai and A(i-1).
Use "xor" bitwise to check these two adjacent bits.
class Solution {
public boolean hasAlternatingBits(int n) {
int val = n & 1;
n >>= 1;
while (n > 0) {
int last = n & 1;
if ((val ^ last) == 0) {
return false;
}
val = last;
n >>= 1;
}
return true;
}
}
class Solution {
public:
bool hasAlternatingBits(int n) {
int val = n & 1;
n >>= 1;
while (n > 0) {
int last = n & 1;
if ((val ^ last) == 0) {
return false;
}
val = last;
n >>= 1;
}
return true;
}
};
class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
val = n & 1
n >>= 1
while n > 0:
last = n & 1
if (val ^ last) == 0:
return False
val = last
n >>= 1
return True
bool hasAlternatingBits(int n) {
int val = n & 1;
n >>= 1;
while (n > 0) {
int last = n & 1;
if ((val ^ last) == 0) {
return false;
}
val = last;
n >>= 1;
}
return true;
}