Share my Java solution with explanation


  • 4
    S
    public int findComplement(int num) {
            // find highest one bit
    	int id = 31, mask = 1<<id;
    	while ((num & mask)==0) mask = 1<<--id;
    		
    	// make mask
    	mask = (mask<<1) - 1;
    		
    	return (~num) & mask;
    }
    

Log in to reply
 

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