我已经开始开发一个 BigInt 类,我现在被困住了。问题是当我尝试将两个不同长度的数字相加时,结果不正确。例如,123 + 1 将返回 223。我知道问题出在哪里,但我需要帮助解决它。
public static BigInt operator +(BigInt n1, BigInt n2)
{
Stack<char> sNew = new Stack<char>();
Stack<char> sTemp = new Stack<char>();
int currentDigit1, currentDigit2, sum;
int carry = 0;
//insert the digits, XXXyyy + ZZZ = first insert ___yyy and then calculate XXX+ZZZ
if (n1.GetLength() > n2.GetLength())
{
while (n1.GetLength() > n2.GetLength())
sNew.Push(n1.sDigits.Pop());
}
else if (n2.GetLength() > n1.GetLength())
{
while (n2.GetLength() > n1.GetLength())
sNew.Push(n2.sDigits.Pop());
}
while (n1.sDigits.Count > 0)
{
currentDigit1 = int.Parse(n1.sDigits.Pop().ToString());
currentDigit2 = int.Parse(n2.sDigits.Pop().ToString());
sum = currentDigit1 + currentDigit2 + carry;
carry = 0;
if (sum > 10)
{
carry = 1;
sum = sum % 10;
}
sNew.Push(char.Parse(sum.ToString()));
}
//if there is a carry, for example 95+18
if (carry > 0)
sNew.Push(char.Parse(carry.ToString()));
//flip the stack
while (sNew.Count > 0)
sTemp.Push(sNew.Pop());
while (sTemp.Count > 0)
sNew.Push(sTemp.Pop());
return new BigInt(sNew);
}
不管这个问题,这种类设计模式有效吗?设计这种类有更好的主意吗?