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.
判断一个数的二进制是否是交替的
一开始就想到了按位取反相加然后判断二进制特性的方法,但是竟然没想到只要右移一位就可以达到这样的效果,真是罪过。
相交之后只要判断形如111111这样的数的特性就可以了
即n & (n+1) == 0
代码如下
public boolean hasAlternatingBits(int n) {
return ((n +(n>>1)) & (n+(n>>1)+1)) == 0;
}