如何使用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