Easy to Understand Java solution by XOR-ing with previous bit to check if its 1


  • 0
    G

    class Solution {
    public boolean hasAlternatingBits(int n) {
    // Save the first bit in previous bit and keep checking if XOR of previous bit and current bit equal to 1 then continue else return false

        int previousBit = (n)&1;
         n=n>>1;
        while(n>0)
        {
    
            if(((n&1)^previousBit)==0)
                return false;
            previousBit = n&1;
            n=n>>1;
        }
        return true;
    }
    

    }


Log in to reply
 

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