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.
解释:
判断一个正整数的二进制是不是01交替的。
1.利用了0和1的交替的特性,进行错位相加(原始的数字向右移动一位),从而组成全1的二进制数;
2.然后再用一个检测全1的二进制数的trick,就是二进制全1的数字a
与上(a+1)
的结果是0
.
因为全1的二进制数加1,就会进一位,并且除了最高位,其余位都是0,跟原数相‘与’就会得0,所以我们可以这样判断。比如n是10101,那么n>>1就是1010,二者相加就是11111,再加1就是100000,二者相‘与’就是0。
3.这种题目还是不要用字符串判断了,考的就是位运算。
python代码:
class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
a=n+(n>>1);
return False if a&(a+1) else True
c++代码:
class Solution {
public:
bool hasAlternatingBits(int n) {
int a=n+(n>>1);
return a&(a+1)?false:true;
}
};
总结:
神奇的位运算。
问号表达式也很有用哦。