Thursday, January 12, 2012

Write a program to add two big number( greater than 100 digit)

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

string add(char x[],char y[])
{
int i,j,k,t1,t2,carry,len1,len2;
char tem[1009];
len1=strlen(x);
len2=strlen(y);
carry=k=0;
for(i=len1-1,j=len2-1;i>=0||j>=0;i--,j--)
{
    t1=t2=0;
if(i>=0) t1 = x[i] - 48;
if(j>=0) t2 = y[j] - 48;
tem[k++] = ( ( t1+t2+carry ) % 10 ) + 48;
carry=(t1+t2+carry)/10;
}
while(carry!=0)
{
tem[k++] = (carry%10) + 48;
carry/=10;
}
tem[k]='\0';
reverse(&tem[0],&tem[k]);
return tem;
}

int main()
{
char ch[1009],ch1[1009];
string result;
while(scanf("%s%s",&ch,&ch1)==2)
{
result = add(ch,ch1);
cout << result << endl;
}
return 0;
}


/*
Input:
1 90
9 1
999 1
Output:
91
10
1000
*/

No comments:

Post a Comment