转载自http://hi.baidu.com/liuflin/blog/item/207e7ceffdefae11fcfa3cd0.html
#include <iostream>
#include <string>
using namespace std;
class ds
{
public:
void equal(string x,string y,int n1,int n2);
void nequal(string x,string y,int n1,int n2);
private :
string s1,s2;
};
void ds::equal (string s1,string s2,int n1,int n2)
{//两个字符串一样长的时候;
int flag =0;
int i;
int sum =0;
int k = 0;
int add[1000];
for(i=0;i<n1;i++)
{
sum = (s1[n1-1-i]-48)+(s2[n1-1-i]-48)+flag;
if (sum >= 10)
{
sum -= 10;
flag = 1;
}
else
flag = 0;
add[i] = sum;
}
if(flag==1)
add[i++] = flag;//最后加上一位进位;
for (i--;i>=0;i--)
cout <<add[i];
}
void ds::nequal(string s1,string s2,int n1,int n2)
{//两个字符串不一样长的时候;
int flag = 0;
int i;
int sum = 0;
int k = 0;
int add[1000];
if (n1 < n2)
{
for(i=0;i<n1;i++)
{
sum = (s1[n1-1-i]-48)+(s2[n2-1-i]-48)+flag;
if (sum >= 10)
{
sum -= 10;
flag = 1;
}
else
flag = 0;
add[i] = sum;
}
for(;i<n2;i++)
{
sum = s2[n2-1-i]-48 + flag;
if (sum >= 10)
{
sum=0;
flag = 1;
}
else
flag=0;
add[i]=sum;
}
if(flag==1)
add[i++] = flag;//最后加上一位进位;
for (i--;i>=0;i--)
cout <<add[i];
cout<<endl;
}
if (n2 < n1)
{
for(i=0;i<n2;i++)
{
sum = (s2[n2-1-i]-48)+(s1[n1-1-i]-48)+flag;
if (sum >= 10)
{
sum -= 10;
flag = 1;
}
else
flag = 0;
add[i] = sum;
}
for(;i<n1;i++)
{
sum = s1[n1-1-i]-48 + flag;
if (sum >= 10)
{
sum=0;
flag = 1;
}
else
flag=0;
add[i]=sum;
}
if(flag==1)
add[i++] = flag;//最后加上一位进位;
for (i--;i>=0;i--)
cout <<add[i];
cout<<endl;
}
}
int main()
{
ds dashu;
string x1,x2;
cout<<"please input two word:" <<endl;
cin >>x1>>x2;
int n1=x1.length();
int n2=x2.length();
if (n1==n2)
dashu.equal(x1,x2,n1,n2);
else
dashu.nequal(x1,x2,n1,n2);
cout <<endl;
return 0;
}