主要分为以下几个步骤:
初始化数组 -> 输入字符串,并逆序 -> 按位保存到数组里 -> 按位相加,并处理进位 -> 判断最高位是否为0, 并逆序输出
参考代码:
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAX 100
int main()
{
//初始化步骤
int a[MAX] = { 0 };
int b[MAX] = { 0 };
int c[MAX + 1] = { 0 };
//输入相加的字符串,然后逆序(一定要逆序)
string temp_str1, temp_str2;
cin >> temp_str1 >> temp_str2;
int s1_size = temp_str1.size(), s2_size = temp_str2.size();
reverse(temp_str1.begin(), temp_str1.end());
reverse(temp_str2.begin(), temp_str2.end());
//按位存放到数组里去
for (auto i = 0; i < s1_size; i++)
a[i] = temp_str1[i] - '0';
for (auto i = 0; i < s2_size; i++)
b[i] = temp_str2[i] - '0';
//相加长度以最长的字符串来算,然后按位相加,并处理进位问题
int len_max = max(s1_size, s2_size);
for (auto i = 0; i < len_max; i++)
{
c[i] = a[i] + b[i];
if (c[i] >= 10)
{
c[i] -= 10;
c[i + 1] += 1;
}
}
//判断最高位是否为0,然后逆序输出
if (c[len_max] != 0) cout << c[len_max];
for (auto i = 0; i < len_max; i++)
cout << c[len_max - i - 1];
cout << endl;
return 0;
}