关于C#中的大数相乘

/ 0评 / 0

经过验算应该可以的,但放到OJ上会报以下错误:

Unhandled Exception:
System.FormatException: Input string was not in the correct format
  at System.Int32.Parse (System.String s) [0x00000] in <filename unknown>:0 
  at AA1294.Program.Sum (System.String s, Int32 a) [0x00000] in <filename unknown>:0 
  at AA1294.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 大数相乘
{
 class Program
 {
    static void Main(string[] args)
    {
        string a = Console.ReadLine();
        string b = Console.ReadLine();
        string[] bb = new string[b.Length];
        int[] aa = new int[a.Length * b.Length];//用数组表示每一位数字
        for (int i = 0 ; i < b.Length; i++)
        {
            bb[b.Length - i-1] = Sum(a, int.Parse(b[i].ToString()));
        }//把每一位乘上
        for (int i = 0; i < b.Length; i++)
        {
            if (i == 0)
            {
                 for (int j = 0; j < bb[i].Length; j++)
                 {
                      aa[j] += int.Parse(bb[i][j].ToString());
                 }
            }
            else
            {
                 for (int j = 0; j < bb[i].Length ; j++)
                 {
                     aa[j + i] += int.Parse(bb[i][j].ToString());
                 }//换位相加
            }
         }
         for (int i = 0; i < aa.Length; i++)
         {
            while (aa[i] > 9)
            {
                 aa[i + 1] += 1;
                 aa[i] -= 10;
            }
         }
         int c = 0;
         for (int i = aa.Length - 1; i >= 0; i--)
         {
            if (aa[i] != 0)
            {
                 c++;
            }
            if (c!= 0)
            {
                 Console.Write(aa[i]);
            }
         }
         Console.ReadKey();
    }
    public static string Sum(string s, int a) //大数乘以小数
    {
        int[] ai = new int[s.Length + 1];
        string ss = "";
        for (int i = 0; i < s.Length; i++)
        {
             ai[i] = int.Parse(s[i].ToString()) * a;
        }
        for (int i = s.Length - 1; i >= 0; i--)
        {
             while (ai[i] > 9 && i > 0)
             {
                 ai[i] -= 10;
                 ai[i - 1] += 1;
             }
        }
        int c = 0;
        for (int i = ai.Length - 1; i >= 0; i--)
        {
             if (ai[i] != 0)
             {
                 c++;
             }
             if (c != 0)
             {
                 ss += ai[i];
             }
        }
        return ss;
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *