如何使用 C# 找到两个二进制数的和?
要计算两个二进制数的和,首先设置这两个数。
val1 = 11110; val2 = 11100;
现在调用 displaySum() 方法,用来显示 sumL。
sum = displaySum(val1, val2);
我们在方法中设置了一个新数组,用来显示二进制数的每一位。
long[] sum = new long[30];
现在,让我们看看完整的代码来计算二进制数的和,如下所示 −
范例
using System; class Demo { public static void Main(string[] args) { long val1, val2, sum = 0; val1 = 11110; val2 = 11100; Console.WriteLine("Binary one: "+val1); Console.WriteLine("Binary two: "+val2); sum = displaySum(val1, val2); Console.WriteLine("Sum = {0}", sum); } static long displaySum (long val1, long val2) { long i = 0, rem = 0, res = 0; long[] sum = new long[30]; while (val1 != 0 || val2 != 0) { sum[i++] =(val1 % 10 + val2 % 10 + rem) % 2; rem =(val1 % 10 + val2 % 10 + rem) / 2; val1 = val1 / 10; val2 = val2 / 10; } if (rem != 0) sum[i++] = rem; i = i-1; while (i >= 0) res = res * 10 + sum[i--]; return res; } }
输出结果
Binary one: 11110 Binary two: 11100 Sum = 111010
广告