C++, concise code


  • 7
    Z

    The solution is to use bit manipulation. And d is last digit of n.

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.