Programming: How many bits are different in the binary representation of two int (32-bit) integers m and n?
Ideas:
- First, perform a bitwise XOR between m and n. At this time, the same binary bit of m and n is cleared, and the different binary bit is 1.
- Count the number of 1s in the binary bits of the result after the XOR is completed
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int diff_bit(int m, int n)
{
int tmp = m ^ n;
int count = 0;
while (tmp)
{
tmp = tmp & (tmp - 1);
count++;
}
return count;
}
int main()
{
int m, n;
printf("请输入两个数字: ");
scanf("%d %d", &m, &n);
int ret = diff_bit(m, n);
printf("ret=%d\n", ret);
return 0;
}