如何使用 C# 查找两个二进制数字的乘积?


若要查找两个二进制数字的乘积,首先设置它们。

val1 = 11100;
val2 = 10001;

Console.WriteLine("Binary one: "+val1);
Console.WriteLine("Binary two: "+val2);

现在循环以获取乘积。

while (val2 != 0) {
   digit = val2 % 10;
   if (digit == 1) {
      val1 = val1 * factor;
      prod = displayMul(val1, prod);
   } else
   val1 = val1 * factor;
   val2 = val2 / 10;
   factor = 10;
}
Console.WriteLine("Product = {0}", prod);

上面一个 displayMul() 方法被第一个二进制数字调用。

static long displayMul (long val1, long val2) {
   long i = 0, rem = 0, mul = 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)
   mul = mul * 10 + sum[i--];
   return mul;
}

以下是完整代码 −

示例

 在线演示

using System;
class Demo {
   public static void Main(string[] args) {
      long val1, val2, prod = 0;
      long digit, factor = 1;

      val1 = 11100;
      val2 = 10001;

      Console.WriteLine("Binary one: "+val1);
      Console.WriteLine("Binary two: "+val2);

      while (val2 != 0) {
         digit = val2 % 10;
         if (digit == 1) {
            val1 = val1 * factor;
            prod = displayMul(val1, prod);
         } else
         val1 = val1 * factor;
         val2 = val2 / 10;
         factor = 10;
      }
      Console.WriteLine("Product = {0}", prod);
   }

   static long displayMul (long val1, long val2) {
      long i = 0, rem = 0, mul = 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)
      mul = mul * 10 + sum[i--];
      return mul;
   }
}

输出

Binary one: 11100
Binary two: 10001
Product = 111011100

更新时间:2020-06-22

513 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始
广告