Java, bit manipulation solution (move bit from left to right)


  • 0
    C

    Move bits from left to right until meets the beginning 1 of n. Then checking whether the rest of available bits of n are interleaving or not.

    public static boolean hasAlternatingBits(int n) {
            
            int pivot = 1 << 30;
            int count = 30;
            while (count >= 0) {
                
                if ( (n & pivot) > 0) break;
                n = n << 1;
                count --;
            }
            
            // the sign should be n & pivot > 0
            int sign = count % 2;
            
            while (count >= 0) {
                // use count % 2 to check whether the current bit should be 1 or 0
                if ( ( count % 2 == sign && (n & pivot) == 0) || 
                   (count % 2 != sign && (n & pivot) > 0) )
                    return false;
                n = n << 1;
                count --;
            }
            
            return true;
        }
    

Log in to reply
 

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