2013年5月9日 星期四

Number Complement.

Question: 
A complement of a number is defined as 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 101 in binary. The complement of N is 010, which is 2 in decimal. Similarly if N = 50, then complement of N is 13 
Complete the function getIntegerComplement(). This function takes N as it's parameter. The function should return the complement of N.  (The N >=0)


My Answer:  (I am not sure if it is correct.)
int getComplement(int n)
{
    if (n == 0)
        return 1;

    int b = 0;
    int a = n;
    while (a > 0)
    {
        a >>= 1;
        b++;
    };

    int mask = pow(2.0, b) - 1;
    int result = n ^ mask;
    return result;
}

沒有留言:

張貼留言