LeetCode 693. Binary Number with Alternating Bits
考点 | 难度 |
---|---|
Bit Manipulation | Easy |
题目
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
思路
判断n/2
和n%2
是不是一样。
答案
public boolean hasAlternatingBits(int n) {
int cur = n % 2;
n /= 2;
while (n > 0) {
if (cur == n % 2) return false;
cur = n % 2;
n /= 2;
}
return true;
}