Files
python/TangDou/LuoGuBook/第8章模拟与高精度/P1601.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

47 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
/**
* 功能:高精度加法模板
* @param A
* @param B
* @return
*/
vector<int> add(vector<int> &A, vector<int> &B) {
//声明结果数组C
vector<int> C;
//以长的为根基,进行计算
if (A.size() < B.size()) return add(B, A);
//进位
int t = 0;
//列竖式进行计算
for (int i = 0; i < A.size(); i++) {
t += A[i];//进位加法
if (i < B.size()) t += B[i]; //存在这一位,就加
C.push_back(t % 10);//保留余数
t /= 10;//进位
}
//最后可能还有进位
if (t) C.push_back(t);
//返回
return C;
}
int main() {
//以字符串形式读入
string a, b;
cin >> a >> b;
//1、准备动作,将字符串的每一位,反序放入到整数运算数组中
vector<int> A, B, C;
for (int i = a.size() - 1; i >= 0; i--) A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i--) B.push_back(b[i] - '0');
//2、调用模板进行计算
C = add(A, B);
//3、输出结果,需要倒序噢
for (int i = C.size() - 1; i >= 0; i--)printf("%d", C[i]);
return 0;
}