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.
这个题我就是很标准的除二取模,然后比较是否相同,发现速度很慢很慢,看了题解发现又是位运算,我判断相邻的位是否一样,将其右移1位然后和本身异或运算,就是相当于比较每一位与他的前一位是否相同,得出的结果如果位上全是1,也就是都不相同,然后在将结果与(结果+1)做按位与运算,结果全是1的话,与运算结果为0,否则不为零。
class Solution {
public:
bool hasAlternatingBits(int n) {
int tmp = (n^(n>>1));
return (tmp&(tmp+1))==0;
}
};