Java fast solution with bit manipulation


  • 0

    The idea is to move n with 1bit to the right each time and check whether the bit value changes. I think this methods is faster then others.

    class Solution {
        public boolean hasAlternatingBits(int n) {
            boolean isOne = (n & 1) == 1;
            while (n != 0) {
                n = n >> 1;
                if ((n & 1) == 1 && isOne) 
                    return false;
                else if ((n & 1) == 0 && !isOne)
                    return false;
                isOne = !isOne;
            }
            return !isOne;
        }
    }
    

Log in to reply
 

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