Wednesday, March 20, 2013

Add two big numbers


A simple program to add two big numbers -

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

string add(string str1,string str2)
{
string sumstr;

string minstr,maxstr;
if(str1.length() !=str2.length())
{
maxstr = str1.length()>str2.length()?str1:str2;
minstr = str1.length()<str2.length()?str1:str2;
}
else
{
maxstr = str1;
minstr = str2;
}

sumstr = "0"+ maxstr;

string::reverse_iterator minrev = minstr.rbegin();
string::reverse_iterator maxrev = maxstr.rbegin();

string::reverse_iterator sumrev = sumstr.rbegin();
int carry = 0;
while(minrev != minstr.rend())
{
*sumrev += *minrev - '0' + carry;
if(*sumrev > '9')
{
*sumrev -= 10;
carry = 1;
}
else
{
carry = 0;
}
++sumrev;
++minrev;
}

while(sumrev != sumstr.rend() && carry ==1)
{
*sumrev += 1;
if(*sumrev > '9')
{
*sumrev -= 10;
*(sumrev+1) += 1;

if(*(sumrev+1) < '9')
carry = 0;
else
*(sumrev+1) -= 1;
}
else
carry = 0;

++sumrev;
}

if(sumstr.at(0) == '0')
sumstr.erase(0,1);

return sumstr;
}

int main(int argc, char* argv[])
{
while(1)
{
string str1,str2;
cout<<"Enter number1: ";
cin >> str1;
cout<<"Enter number2: ";
cin >> str2;

string result = add(str1,str2);

cout<<"Result: "<<result<<endl;
}
return 0;
}

No comments:

Post a Comment