Intuitive Java AC


  • 0
    J

    Linearly scan num, check the LSB. As long as it's a 1, flip it and store it into a dummy int element (data).
    Finally, shift offset to left by 1 bit to mask the remaining bits. Shift num right by 1.

        public int findComplement(int num) {
            int data = 0, offset = 1;
            
            while(num != 0){
                if((num & 1) != 1){
                    data |= offset;
                }
                offset <<= 1;
                num >>>= 1;
            }
            
            return data;
        }
    
    

Log in to reply
 

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