您的位置:首页 > 编程语言 > C#

C# 大数相乘

2008-03-19 13:41 183 查看
参照 http://blog.csdn.net/qw_study/archive/2006/10/22/1345087.aspx

的改了下..速度提高了近40倍..

using System;
using System.Text;

namespace BigNumberCalculator
{
public class OP
{
public static string Mut(string str1, string str2)
{
int l1 = str1.Length;
int l2 = str2.Length;
int[] re = new int[l1 + l2];
int x;
int y;
for (int i = l1 - 1; i >= 0; i--)
{
x = (int)str1[i] - 48; //等同于x=int.Parse(str1[i].ToString());
for (int j = l2 - 1; j >= 0; j--)
{
y = (int)str2[j] - 48; //等同于y=int.Parse(str2[j].ToString());
re[l1 - i + l2 - j - 2] += x * y; //关键,将单个的乘积放入对应的位置..
}
}

int lastIndex = re.Length - 1; //最高位所在的位置
StringBuilder sb = new StringBuilder(re.Length);
for (int i = 0; i < lastIndex; i++)
{
int t = re[i];
if (t >= 10)
{
re[i + 1] += t / 10;
t %= 10;
//re[i] = t;
}
sb.Insert(0, t.ToString());
}
if (re[lastIndex] != 0)
{
sb.Insert(0, re[lastIndex].ToString());
}
return sb.ToString();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: