BigInteger addition

mvmalderen 0 Tallied Votes 158 Views Share

Intended as a replacement for this old crap of myself ;)
Note: no error checking provided, if you need it, then you can easily implement it yourself :)

#include <iostream>
#include <string>
using namespace std;

struct DigitPair
{
  unsigned digitA;
  unsigned digitB;
  
  DigitPair() {
    digitA = 0;
    digitB = 0;
  }
};

class DigitIterator
{
private:
  string s1;
  string s2;
  int pos1;
  int pos2;
public:
  DigitIterator(const string &str1, const string &str2) {
    s1 = str1;
    s2 = str2;
    pos1 = s1.length() - 1;
    pos2 = s2.length() - 1;
  }
  
  DigitPair nextDigits() {
    DigitPair dp;
  
    if ( pos1 >= 0 )
      dp.digitA = s1[ pos1-- ] - '0';
    if ( pos2 >= 0 )
      dp.digitB = s2[ pos2-- ] - '0';
  
    return dp;
  }
  
  bool hasDigits() {
    return ( pos1 >= 0 || pos2 >= 0 );
  }
};

string add(string &n1, string &n2);

int main()
{
  string n1, n2;
  cout << "Enter two integers: ";
  cin >> n1 >> n2;
  cout << n1 << " + " << n2 << " = ";
  cout << add(n1, n2) << endl;
}

string add(string &n1, string &n2)
{
  DigitIterator iter(n1, n2);
  string result;
  bool carry = false;
  
  while ( iter.hasDigits() || carry )
  {
    DigitPair dp;
    dp = iter.nextDigits();
  
    int sum = dp.digitA + dp.digitB;
  
    if ( carry )
    {
      sum++;
      carry = false;
    }
  
    if ( sum > 9 )
    {
      sum = sum - 10;
      carry = true;
    }
  
    result = (char)(sum + '0') + result;
  }
  
  return result;
}