解题思路
将n的二进制数存到栈中,然后除去前导0,再将栈中的数据依次出栈,判断是否交替进行。
相关代码
class Solution {
public boolean hasAlternatingBits(int n) {
Stack<Integer> stack = new Stack<>();
for(int i=0;i<32;i++) stack.push(n>>i&1);
while(stack.peek()==0) stack.pop();
int flag=1;
while(!stack.isEmpty()){
int temp=flag;
if(stack.peek()==1) temp=0;
else temp=1;
stack.pop();
if(temp==flag) return false;
flag=temp;
}
return true;
}
}