私はBigIntクラスの開発を始めましたが、今は行き詰まっています。問題は、長さが異なる2つの数値を加算しようとすると、結果が正しくないことです。たとえば、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);
}
この問題に関係なく、クラス設計のこのパターンは効果的ですか?この種のクラスを設計するためのより良いアイデアはありますか?