如何使用 C# 查找两个二进制数的和?
若要查找两个二进制数的和,首先设置它们。
val1 = 11110; val2 = 11100;
现在调用用于显示 sumL 的 displaySum() 方法。
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
广告