大数相加:
直接上代码。
/**大数相加**/
#include<iostream>
#include<stack>
#include<string>
using namespace std;
//判断是否有进位
int judge(int a)
{
return a > 9 ? 1 : 0;
}
int main()
{
int carry = 0;
int temp1, temp2, temp3;
string a, b;
cin >> a >> b;
stack<char>a1, b1;
stack<int>result;
for (auto i : a)
{
a1.push(i);
}
for (auto i : b)
{
b1.push(i);
}
while ((a1.size() != 0) && (b1.size() != 0))
{
temp1 = a1.top() - 48;
temp2 = b1.top() - 48;
a1.pop();
b1.pop();
temp3 = temp1 + temp2 + carry;
carry = judge(temp3);
result.push(temp3 % 10);
}
if ((a1.size() == 0) && (b1.size() == 0))
{
if (carry == 1)
{
result.push(carry);
}
}
else
{
stack<char>c1 = a1.size() == 0 ? b1 : a1;
while (c1.size() != 0)
{
int tmp = c1.top() - 48;
if (carry == 1)
{
result.push(carry + tmp);
c1.pop();
}
else
{
result.push(tmp);
c1.pop();
}
}
}
while (result.size() != 0)
{
cout << result.top();
result.pop();
}
cout << endl;
cout << "对比:" << endl;
long long a2, b2;
cin >> a2 >> b2;
cout << a2 + b2 << endl;
}
原理图:
知乎回答:
https://www.zhihu.com/question/268903307/answer/345805873