693. Binary Number with Alternating Bits - LeetCode
Question
693. Binary Number with Alternating Bits
Solution
思路:输入一个整数,它的二进制01交替出现,遍历其二进制字符串,下一个与上一个不等,返回true,如果有相等的就返回false
Java实现:
public boolean hasAlternatingBits(int n) {
char last = '2'; // 非0非1即可
for (char c : Integer.toBinaryString(n).toCharArray()) { // int转二进制字符串
if (c == last) return false;
last = c;
}
return true;
}