Java detailed bit manipulation


  • 0
    M
    public int findComplement(int num) {
            /*move 30 times to the left. because there are 32bits and starts at 1bit, and the most significant bit is used for sign. 
            so there are total 30 times moves we can do.*/
            int mask = 1 << 30;
            
            /*move 30 times to the right, and check the first set bit.*/
        	for(int i = 0; i < 30; i++) {
        		if((num & mask) == mask)
        			break;
        		else 
        			mask = mask >> 1;
        	}
        	
        	int result = 0;
        	
        	/*finish right shifting until mask becomes zero. When the current bit is zero, then add the mask to the result.*/
        	while (mask > 0) {
        		if ((num & mask) == 0) 
        			result += mask;
        			
        		mask = mask >> 1;
        	}
        	return result;
        }

Log in to reply
 

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