兩個很大的數相加,可以用兩個字符串str1和str2進行操作,參考程序如下:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(void)
{
string str1,str2;
stack<int>stack_ex;
int str1_length,str2_length;
int carry = 0;//進位的控制
int tmp;
while(cin >> str1 >> str2)
{
str1_length = str1.size();
str2_length = str2.size();
int i = str1_length - 1;
int j = str2_length - 1;
for(; i >= 0 && j >= 0; i--,j--)
{
tmp = str1[i] - 0 + str2[j] - 0 + carry;
if(tmp < 10)
{
carry = 0;
stack_ex.push(tmp);
}
else
{
carry = 1;
stack_ex.push(tmp % 10);
}
}
if(str1_length >= str2_length)
{
for(; i >= 0; i--)
{
tmp = str1[i] - 0 + carry;
if(tmp < 10)
{
carry = 0;
stack_ex.push(tmp);
}
else
{
carry = 1;
stack_ex.push(tmp % 10);
}
}
}
else
{
for(; j >= 0; j--)
{
tmp = str2[j] - 0 +carry;
if(tmp < 10)
{
carry = 0;
stack_ex.push(tmp);
}
else
{
carry = 1;
stack_ex.push(tmp % 10);
}
}
}
while(!stack_ex.empty())
{
cout<< stack_ex.top();
stack_ex.pop();
}
cout<<endl;
}
return 0;
}