写一个大数加法的方法,在方法里你可以模拟加法来实现。 比如把两个大数分别放到两个数组: x=A的位数和B的位数中的大者+1 string[] NumA = new string[x]; string[] NumB = new string[x]; 把两个数分别右对齐压入数组,前面补0声明一个数组来存放结果 string[] NumResult = new string[x];//初始化所有位为0 然后循环来加: for(int i = x-1;i>=0;i--) { int a = Convert.ToInt32(NumA[i]); int b = Convert.ToInt32(NumB[i]); if(a+b<10) NumResult[i] += a+b; else { NumResult[i] += a+b-10; NumResult[i-1] += 1; } }//最后得出的NumResult即为大数之和。 基本思路如此,可以试一下。
其实也可以把string[]改为char[]。
public string BigSum(string a,string b) { string strResult = string.Empty ; int len = a.Length>=b.Length?a.Length+1:b.Length+1; char[] Result = new char[len] ; for(int c = 0;c<Result.Length;c++) { Result[c] = '0'; } //字符串前面补0 string NumA = new string('0',len)+a; NumA = NumA.Substring(NumA.Length-len); string NumB = new string('0',len)+b; NumB = NumB.Substring(NumB.Length-len); int iFlow = 0;//进位
比如把两个大数分别放到两个数组:
x=A的位数和B的位数中的大者+1
string[] NumA = new string[x];
string[] NumB = new string[x];
把两个数分别右对齐压入数组,前面补0声明一个数组来存放结果
string[] NumResult = new string[x];//初始化所有位为0
然后循环来加:
for(int i = x-1;i>=0;i--)
{
int a = Convert.ToInt32(NumA[i]);
int b = Convert.ToInt32(NumB[i]);
if(a+b<10)
NumResult[i] += a+b;
else
{
NumResult[i] += a+b-10;
NumResult[i-1] += 1;
}
}//最后得出的NumResult即为大数之和。
基本思路如此,可以试一下。
{
string strResult = string.Empty ;
int len = a.Length>=b.Length?a.Length+1:b.Length+1;
char[] Result = new char[len] ;
for(int c = 0;c<Result.Length;c++)
{
Result[c] = '0';
}
//字符串前面补0
string NumA = new string('0',len)+a;
NumA = NumA.Substring(NumA.Length-len);
string NumB = new string('0',len)+b;
NumB = NumB.Substring(NumB.Length-len); int iFlow = 0;//进位
for(int i = len-1;i>=0;i--)
{
int iA = Convert.ToInt32(NumA[i].ToString()) ;
int iB = Convert.ToInt32(NumB[i].ToString()) ; int iSum = Convert.ToInt32(Result[i].ToString())+iA+iB+iFlow;
if(iSum < 10)
{
Result[i] = Convert.ToChar(Convert.ToInt32(Result[i])+iA+iB+iFlow) ;
iFlow = 0;
}
else
{
Result[i] = Convert.ToChar(Convert.ToInt32(Result[i])+iA+iB+iFlow-10*(iSum/10)) ;
iFlow = iSum/10;
}
}
for(int r = 0;r<Result.Length;r++)
{
if(strResult != string.Empty || Result[r] != '0')
strResult+= Result[r].ToString() ;
}
return strResult ;
}