</pre><pre name="code" class="cpp">#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
int main() {
string s1, s2, ss1 , ss2;
cin >> s1 >> s2;
int n = s1.size(); //逆置字符串
int m = s2.size();
for (int i = 0; i < n; i++)
{
ss1 = s1[i] + ss1;
}
for (int i = 0; i < m; i++)
{
ss2 = s2[i] + ss2;
}
if (n > m) //补齐位数
{
for (int i = 0; i < n-m; i++)
{
ss2 = ss2 + "0";
}
}
else {
for (int i = 0; i < m-n; i++)
{
ss1 = ss1 + "0";
}
}
int add, mid = 0; //模拟计算
string sum, min;
int r = n > m ? n : m;
for (int i = 0; i < r; i++)
{
add = mid + ss1[i] - '0' + ss2[i] - '0';
if (add >= 10)
{
mid = 1;
add = add - 10;
min = add + '0';
sum = min + sum;
}
else {
min = add + '0';
sum = min + sum;
mid = 0;
}
}
if (mid == 1) //判断最后一位为10以上的情况
{
sum = "1" + sum;
}
cout << sum << endl;
}
大数相加问题
最新推荐文章于 2020-04-09 01:24:08 发布