如何在 C# 中不使用任何方法查找两个二进制数的和?
首先,声明并初始化两个变量与二进制数。
val1 = 11010; val2 = 10100; Console.WriteLine("Binary one: " + val1); Console.WriteLine("Binary two: " + val2);
要获取和,循环直到两个值都为 0。
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; }
现在,我们来看一下完整的代码,以找到两个二进制数的和。
示例
using System; class Demo { public static void Main(string[] args) { long val1, val2; long i = 0, rem = 0; long[] sum = new long[30]; val1 = 11010; val2 = 10100; Console.WriteLine("Binary one: " + val1); Console.WriteLine("Binary two: " + val2); 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; Console.Write("Sum = "); while (i >= 0) Console.Write(sum[i--]); } }
输出
Binary one: 11010 Binary two: 10100 Sum = 101110
广告