题目描述:
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
思路:
n = 5: 101
n >> 1: 10
a = n + (n >> 1) = 111
a & (a + 1) == 0
class Solution {
public boolean hasAlternatingBits(int n) {
int a = n + (n >> 1);
return ((a & (a + 1)) == 0);
}
}
思路二:
class Solution {
public boolean hasAlternatingBits(int n) {
//int last = n % 2;
int last = n & 1;
int cur;
//n = n / 2;
n = n >> 1;
while (n > 0)
{
//cur = n % 2;
cur = n & 1;
if (cur == last)
return false;
last = cur;
//n = n / 2;
n = n >> 1;
}
return true;
}
}