判断一个数的位级表示是否不会出现连续的0和1
问题
给定一个正整数,检查它是否有交替的位:也就是说,如果两个相邻的位总是有不同的值。
示例 1:
Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
示例 2:
Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
示例 3:
Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
代码
对于 1010 这种位级表示的数,把它向右移动 1 位得到 101,这两个数每个位都不同,因此异或得到的结果为 1111。
public boolean hasAlternatingBits(int n) {
int a = (n ^ (n >> 1));
return (a & (a + 1)) == 0;
}