An interview question--how many bits are different in the binary representation of two int (32-bit) integers m and n

1. Problem description

十进制4
0100
十进制8
1000

二进制不同的
0100
1000

有两位不同

normal algorithm

1. Two numbers and 1, take out the last digit of the two numbers, compare whether they are the same, until the right shift 32 times,

    for (int i = 0; i < 32; i++)
    {
        if ((m & 1) != (n & 1))
        {
            count++;
        }
        m = m >> 1;
        n = n >> 1;
    }

Eye-catching machine algorithms

0100
1000
1100//异或,结果12,不同的位全部置1

1100 & 1011
12 &(12-1)
0100//异或结果

4&(4-1)
0100&0011
0000//异或结果

Harder to imagine, harder to understand

    u = m^n;  //m和n异或
    while (u)   //相当于找出一个数;二进制中1的个数
    {
        count++;
        u = u & (u - 1);
    }

Guess you like

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