Java, probably a poor solution, but an approach I haven't seen


  • 1
    K
    class Solution {
        public int findComplement(int num) {
            /*
            *   n is the number of leading zeros beyond what 
            *   is needed to represent the number.
            *   (5.toBinaryString : '101')
            */
            int n = 32 - Integer.toBinaryString(num).length();
            
            // shift out the leading zeros
            num = num << n;
            // perform the complement
            num = ~num;
            // shift the result back to the correct position
            num = num >> n;        
            
            return num;
        }
    }
    

Log in to reply
 

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