比较两个数二进制序列有几位不同

时间:2022-04-23 19:55:50

两个int(32位)整数m和n的二进制表达中,有多少个位(bit)不同? 
输入例子:
1999 2299
输出例子:7

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <windows.h>

int main()
{
int arr1[32] = { 0 };
int arr2[32] = { 0 };
int num1 = 0; int num2 = 0;
printf("请输入两个数:");
scanf("%d %d", &num1, &num2);
int i = 0;
for (i = 31; i >= 0; i--)
{
arr1[i] = (num1 >> i) & 1;
}
for (i = 31; i >= 0; i--)
{
arr2[i] = (num2 >> i) & 1;
}
int count = 0;
for (i = 31; i >= 0; i--)
{
if (arr1[i] != arr2[i])
{
count++;
}
}
printf("%d的二进制序列为:\n", num1);
for (i = 31; i >= 0; i--)
{
printf("%d", arr1[i]);
}
printf("\n");
printf("%d的二进制序列为:\n", num2);
for (i = 31; i >= 0; i--)
{
printf("%d", arr2[i]);
}
printf("\n");
printf("%d和%d二进制序列中有%d位不同\n", num1, num2, count);
system("pause");
return 0;
}

比较两个数二进制序列有几位不同