问题描述:
世界上有10种人,一种懂二进制,一种不懂。那么你知道两个int32整数m和n的二进制表达,有多少个位(bit)不同么?
输入例子:1999 2299
输出例子:7
分析:将两个整数逐位进行比较,累加不同位的个数,直至两个数都为0.
方法一:
比较两个数的最后一位,然后分别右移一位,直至两个数都为0.
源代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int countBitDiff(int m, int n)
{
int count = 0;
while (m != 0 || n != 0)
{
if ((m & 0x1) != (n & 0x1))
++count;
m >>= 1;
n >>= 1;
}
return count;
}
int main()
{
int m, n;
while (scanf("%d %d", &m, &n) == 2)
{
printf("%d\n", countBitDiff(m, n));
}
printf("%s %s\n", __DATE__, __TIME__);
system("pause");
return 0;
}
1999 2299
7
123456 654321
8
^Z
Aug 28 2016 20:02:54
请按任意键继续. . .
方法二
此方法要多感谢下边第一位评论网友的点拨,先将两个数进行异或,然后统计异或得到的结果中1的位数。
源代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int countBitDiff(int m, int n)
{
int temp = m^n;
int count = 0;
while (temp)
{
++count;
temp = temp&(temp - 1);
}
return count;
}
int main()
{
int m, n;
while (scanf("%d %d", &m, &n) == 2)
{
printf("%d\n", countBitDiff(m, n));
}
printf("%s %s\n", __DATE__, __TIME__);
system("pause");
return 0;
}
1999 2299
7
^Z
Aug 29 2016 16:07:15
请按任意键继续. . .