class Solution {
public boolean hasAlternatingBits(int n) {
if(n==0){
return true;
}
int preBit = n&1;
n>>>=1;
while(n>0){
int curBit = n&1;
if(preBit==curBit){
return false;
}
preBit = curBit;
n>>>=1;
}
return true;
}
}
straightforward java solution!

@tiandiao123 thanks for sharing your solution, could you please explain why you return true when n is 0?

@claytonjwong Because 0 is assumed to be true in this question. If 0 is not true, based on 5's binary digit:0000,0000,0000,0000,0000,0000,0000,0101, 5 will also be false. But 5 is true!