第一种方法:
<pre name="code" class="cpp">#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int diff_bits(int x,int y)
{
int i = 0;
int count = 0;
int a[32] = {0};
int b[32] = {0};
for(i=0; i<32; i++)
{
a[i] = x % 2;//取出x二进制中的最低位,存到数组a中
x /= 2;//去掉x二进制中的最低位
}
for(i=0; i<32; i++)
{
b[i] = y % 2;
y /= 2;
}
for (i=0; i<32; i++)
{
if (a[i] ^ b[i] == 1)//如果对应位不同,则count加1
{
count++;
}
}
return count;
}
int main()
{
int x = 0;
int y = 0;
int count = 0;
printf("please Enter (x,y)");
scanf("%d %d",&x, &y);
count = diff_bits(x,y);
printf("diffs = %d",count);
system("pause");
return 0;
}
第二种方法:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"windows.h"
int Diff_Bits(int x, int y)
{
int count = 0;
int tmp = x ^ y;//取出x和y的不同
while (tmp)
{
tmp &= (tmp - 1);//消掉tmp最低位中的1
count++;//计数器计算1的个数
}
return count;
}
int main()
{
int a = 0;
int b = 0;
int bits = 0;
printf("please Enter (a,b):");
scanf("%d %d",&a,&b);
bits = Diff_Bits(a, b);
printf("diffs = %d",bits);
system("pause");
return 0;
}