Reputation: 6051
I have started to develop a BigInt class and i'm stuck right now. The problem is that when I try to add two numbers with different lengths, the result is not correct. For example, 123 + 1 will return 223. I know where the problem is, but I need help on fixing it.
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);
}
Regardless of this problem, is this pattern of the class design is effective? Is there better idea for designing this kind of class?
Upvotes: 1
Views: 302
Reputation: 726929
This is a rather wasteful representation, using full eight bits for a single decimal digit - roughly a 60% waste of space!
Even if you stay with this representation, you should consider switching the internal representation from a Stack<char>
to a List<char>
, with the least significant digit stored at position 0
, the digit for the tens stored at position 1
, and so on. This will let you implement addition with a single loop that adds digits at the same position if both digits are available, or adds the carry to the digit of the longer number.
A better representation would be to use a base-256 system, and store individual "digits" as an array of bytes.
Note that the addition is not the trickiest operation to implement: wait till you hit multiplication and division! To take a peek at the complexity that you would need to address, download Java's implementation of BigInteger
.
I am assuming that you are doing this for fun, not as part of a real project. Otherwise, there is no excuse for not using .NET's built-in representation of BigInteger
.
Upvotes: 1