【Leetcode_easy】693. Binary Number with Alternating Bits

problem

693. Binary Number with Alternating Bits

solution1:

class Solution {
public:
    bool hasAlternatingBits(int n) {
        int bit = -1;
        while(n>0)
        {
            /*
            errr...
            if(n&1 && bit==1) return false;
            else if(n&1) bit = 1;
            if(n&1==0 && bit==0) return false;
            else if(n&1==0) bit = 0;
            */
            if(n&1==1)
            {
                if(bit==1) return false;
                bit = 1;
            }
            else 
            {
                if(bit==0) return false;
                bit = 0;
            }
            n >>= 1;//err.
        }
        return true;
    }
};

solution2:

通过异或操作判断最低位是否在0/1之间转换进行。

class Solution {
public:
    bool hasAlternatingBits(int n) {
        int d = (n&1);
        while((n&1)==d)
        {
            d ^= 1;//
            n >>= 1;
        }
        return n==0;
    }
};

参考

1. Leetcode_easy_693. Binary Number with Alternating Bits;

2. Grandyang;

原文地址:https://www.cnblogs.com/happyamyhope/p/11091404.html