Acwing791.高精度加法

题解

高精度加法
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
vector<int> add(vector<int> &a, vector<int> &b)
{
if(a.size() < b.size()) return add(b, a);
int t = 0;
vector<int> c;
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()
{
vector<int> A;
vector<int> B;
string a, b;
cin >> a >> b;
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');
auto C = add(A, B);
for(int i = C.size() - 1; i >= 0; --i) printf("%d",C[i]);
puts("");
return 0;
}
压九位做法
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
const int base = 1000000000;
vector<int> add(vector<int> &a, vector<int> &b)
{
if(a.size() < b.size()) return add(b, a);
vector<int> c;
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 % base);
t /= base;
}
if(t) c.push_back(t);
return c;
}
int main()
{
vector<int> A;
vector<int> B;
string a, b;
cin >> a >> b;
for(int i = a.size() - 1, j = 0, t = 1, s = 0; i >= 0; --i)
{
s += (a[i] - '0') * t;
t *= 10, j++;
if(j == 9 || i == 0)
{
A.push_back(s);
s = 0, t = 1, j = 0;
}
}
for(int i = b.size() - 1, j = 0, t = 1, s = 0; i >= 0; --i)
{
s += (b[i] - '0') * t;
t *= 10, j++;
if(j == 9 || i == 0)
{
B.push_back(s);
s = 0, t = 1, j = 0;
}
}
auto C = add(A, B);
cout << C.back();
for(int i = C.size() - 2; i >= 0; --i) printf("%09d",C[i]);
puts("");
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)