https://leetcode.com/problems/binary-number-with-alternating-bits/description/
题解:给出一个整数,判断其二进制是否会出现连续的0或者1,如果出现,返回true,如果没有,返回false。以下是三种解法。第一种是我自己写的,第二第三种是借鉴的。第三个不理解的话可以用一个数带进入算一下就会懂的。
第一种:
class Solution {
public boolean hasAlternatingBits(int n) {
int bit = n%2;
System.out.println(bit);
n/=2;
while(n != 0) {
System.out.println(bit);
if(n%2 == bit)
return false;
bit = n%2;
n/=2;
}
return true;
}
}
第二种:
class Solution {
public boolean hasAlternatingBits(int n) {
String bits = Integer.toBinaryString(n);
for (int i = 0; i < bits.length() - 1; i++) {
if (bits.charAt(i) == bits.charAt(i+1)) {
return false;
}
}
return true;
}
}
第三种:
class Solution {
public boolean hasAlternatingBits(int n) {
return ( (n + (n>>1) + 1) & ( n + (n>>1) )) == 0;
}
}