将两个十进制数转换成二进制后判断每位是否相同的方法
发布网友
发布时间:2024-03-25 21:29
我来回答
共2个回答
热心网友
时间:2024-04-11 18:41
public static void CowCal()
{
Console.WriteLine("将两个十进制数转换成二进制后判断每位是否相同的方法 ,如520 和744 转换成二进制后共有三位不相同;");
Console.Write("请输入M:");
int m = Convert.ToInt32(Console.ReadLine());
Console.Write("请输入N:");
int n = Convert.ToInt32(Console.ReadLine());
int total = Cal(m, n);
Console.WriteLine("结果是:" + total.ToString() + "位");
}
private static int Cal(int m, int n)
{
int count = 0;
string maxs = "";
string mins = "";
int max = m, min = n;
if (m < n)
{
max = n;
min = m;
}
int maxEx;
int minEx;
int tmpMax = max;
int tmpMin = min;;
do{
maxEx = tmpMax % 2;
maxs = maxEx.ToString() + maxs;
tmpMax = tmpMax/2;
if (tmpMin > 0)
{
minEx = tmpMin % 2;
mins = minEx.ToString() + mins;
tmpMin = tmpMin / 2;
if (maxEx == minEx)
{
continue;
}
}
count++;
}
while (tmpMax > 0);
Console.WriteLine(max.ToString() + ":" + maxs);
Console.WriteLine(min.ToString() + ":" + mins);
return count;
}
热心网友
时间:2024-04-11 18:41
可以先把这两个数按位异或后在计算有多少个一,下面是C语言来实现
#include <stdio.h>
int main()
{
int a,b,i,sum=0,bits=0;
scanf("%d %d",&a,&b);
if(a>b)
{
i=a;
}
else
{
i=b;
}
while(i!=0)
{
i/=2;
++bits;
}
a^=b;
for(i=0;i<bits;i++)
{
b=a%2;
if(0==b)
++sum;
a/=2;
}
printf("有%d位相同,有%d位不相同\n",sum,bits-sum);
return 0;
}