sundeepblue
4/11/2014 - 2:00 AM

get the complement of a unsigned integer by bit operation

get the complement of a unsigned integer by bit operation

/*
A complement of a number is defined as the inversion (if the bit value = 0, change it to 1 and vice-versa) of all 
bits of the number starting from the leftmost bit that is set to 1. For example, if N = 5, N is represented as 101 
in binary. The complement of N is 010, which is 2 in decimal notation. Similarly if N = 50, then the complement 
of N is 13. Complete the function getIntegerComplement(). This function accepts N as parameter. The function should 
return the complement of N.The section of the program which parses the input and displays the output will be handled 
by us. Your task is to complete the body of the function or method provided, and to return the correct output.

Constraints :
0 ≤ N ≤ 100000.

Sample Test Cases: 

Input #00:
50

Output #00:
13

Explanation:

50 in decimal form equals: 110010 when converted to binary.
Inverting the bit sequence: 001101. This is the binary equivalent of decimal 13.

Input #01:
100

Output #01:
27

Explanation:

The bit sequence for 100 is 1100100. Inverting the sequence gives 0011011 which is the binary equivalent of decimal 27.
*/

// idea: generate a mask.
// eg: N =  00000000000000000000000000010001
            

int getIntegerComplement(unsigned int N) {  // eg:  N= 00000000000000000000000000010001
    if(N == 0) return 0;    
    unsigned int m = 1<<31;                 //      m= 10000000000000000000000000000000
    while((m&N) == 0)
        m >>= 1;                            // now  m= 00000000000000000000000000100000
    m <<= 1;                                // now  m= 00000000000000000000000001000000
    m -= 1;                                 // now  m= 00000000000000000000000000111111
    N ^= m;                                 // now, use XOR 1, since 1^1=0, 0^1=1.
    return N;                               // now  N= 00000000000000000000000000001110
}