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.
Example 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
Example 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
Example 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
Example 4:
Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
解析
如果temp
(假设有n
位)的相邻两位不相同,那么temp ^ (temp << 1)
就会得到n
位的1
的max
。max
与1
相加后,得到n + 1
位,最高位为1
,其余位为0
,这样与temp
进行&
运算后得到的结果为0
。
1.
Input:5
,则二进制为101
。
101 << 1 = 010
<= 101
右移1位(除以2)
101 ^ 010 = 111
<= 101
和010
异或
111 + 1 = 1000
<= 111
与1
相加
101 & 1000 = 0000
。
2.
Input:11
,则二进制为1011
。
1011 << 1 = 0101
<= 1011
右移1位(除以2)
1011 ^ 0101 = 0010
<= 1011
和0101
异或
0010 + 1 = 0011
<= 0010
与1
相加
1011 & 0011 = 0011
。
解决
class Solution {
public:
bool hasAlternatingBits(int n) {
int temp = n ^ (n >> 1);
if ((temp & (temp + 1)) == 0) {
return true;
} else {
return false;
}
}
};