693. Binary Number with Alternating Bits

题意

给定一个正整数n,判断在二进制下的n,邻位的数字是否不一样。如5的二进制位101,邻位都不一样。

思路

既然邻位不一样,那么在右移一位后再与n异或,那么结果将会全是1。

class Solution {
    public boolean hasAlternatingBits(int n) {
        int z = (n>>1)^n;
        
        while (z > 0) {
            if ((z&1) != 1) {
                return false;
            }
            z >>= 1;
        }
        
        return true;
    }
}
原文地址:https://www.cnblogs.com/sevenun/p/8989146.html