标签:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BigNumberMultiplication
{
class Program
{
static void Main(string[] args)
{
try
{
int first = 4916;
int second = 12345;
long result = first * second;
Console.WriteLine(string.Format("{0} * {1} = {2}\n\n", first.ToString(), second.ToString(), result.ToString()));
string firstStr = "100000000000000000000";
string secondStr = "100000000000000000000";
string resultStr = MultipFunction(firstStr, secondStr);
Console.WriteLine("The result is: {0}", resultStr.TrimStart(‘0‘));
Console.WriteLine("The length of the result is: {0}", resultStr.TrimStart(‘0‘).Length);
Console.ReadKey();
}
catch (Exception ex)
{ }
}
//大数据乘法
private static string MultipFunction(string firstNumStr, string secondNumStr)
{
try
{
int firstNumLength = firstNumStr.Length;
int secondNumLength = secondNumStr.Length;
int resultNumLength = firstNumLength + secondNumLength;
int[] firstNumValue = new int[firstNumLength];
int[] secondNumValue = new int[secondNumLength];
int[] resultNumValue = new int[resultNumLength];
//遍历字符串,将每一位的字符转换成为int整形插入整形数组中
for (int i = 0; i < firstNumLength; i++)
{
firstNumValue[i] = firstNumStr[i] - 48;
}
for (int i = 0; i < secondNumLength; i++)
{
secondNumValue[i] = secondNumStr[i] - 48;
}
//定义的整形数组初始化各个位就是0;所以下面赋0的过程可以省略
for(int i = 0; i < resultNumLength; i++)
{
resultNumValue[i] = 0;
}
//算法的核心(小学笔算乘法的流程),将两个数按位进行相乘-->组合成结果的整形数组
//然后对此结果整形数组进行遍历,结果的低位取整附加给临近的高位,低位取余赋给本低位(注:这里说的低位恰好是数组的高位,即数组下标大的位)
for (int i = firstNumLength - 1; i >= 0; i--)
{
for (int j = secondNumLength - 1; j >= 0; j--)
{
resultNumValue[i + j + 1] += firstNumValue[i] * secondNumValue[j];
resultNumValue[i + j] += resultNumValue[i + j +1] /10;
resultNumValue[i + j + 1] = resultNumValue[i + j + 1] % 10;
}
}
//将整形数组转化成字符数组
char[] temp = new char[resultNumLength];
for (int i = 0; i < resultNumLength; i++)
{
temp[i] = (char)(resultNumValue[i] + 48);
}
//将字符数组转化为字符串
string resultStr = new string(temp);
return resultStr;
}
catch (Exception ex)
{
return string.Empty;
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/jameslif/p/4976187.html