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: 11 Output: False Explanation: The binary representation of 11 is: 1011.
bool hasAlternatingBits(int n) {
if (n == 1 || n == 2) return true;
int mask = n << 1;
int flag = n ^ mask;
flag = (n & 0x1)?(flag & (flag+1)):(flag & (flag+2));
if (flag)
return false;
else
return true;
}
or
bool hasAlternatingBits(int n) {
int mask = n >> 1;
int flag = n + mask;
if (flag&(flag+1))
return false;
else
return true;
}
No comments:
Post a Comment