476. Number Complement - Invert the most significant bit

https://leetcode.com/problems/number-complement/

analyze

That is to say, you can invert the bit after the highest bit of a number. The key is to find the highest bit, simple bit operation, and it can be done in ten minutes. The use of bit operations needs to be strengthened. God skills.

realize one

int findComplement(int num) {
    int i = 0;
    int tmp=0;
    int max=0;
    for(i=0;i<32;i++)
    {
        tmp=0x80000000>>i;
        if((num &tmp) == tmp)
        {
            max=i;
            break;
        }
    }

    num = ~num;
    num &= 0xFFFFFFFF>>max;

    return num; 
}

realization two

int findComplement(int num) {
    int tmp = num;

    /* 将最高位后面的位都置为1 */  
    tmp |= (tmp>>1);
    tmp |= (tmp>>2);
    tmp |= (tmp>>4);
    tmp |= (tmp>>8);
    tmp |= (tmp>>16);

    num = ~num;
    num &= tmp;

    return num; 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325482382&siteId=291194637