C++高精度算法--加法

一.头文件

1.<iostream>

2.<cstdio>

3.<cstring>

*cstring 速度更快,尽量不用string

二.代码

cpp 复制代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=1e5+10;
char s1[N],s2[N];
int a[N],b[N],c[N],lena,lenb,MAX,x;
int main(){
	cin>>s1>>s2;
	lena=strlen(s1);
	lenb=strlen(s2);
	MAX=max(lena,lenb);
	for(int i=0;i<lena;i++) a[i]=s1[lena-1-i]-'0'; 
	for(int i=0;i<lenb;i++) b[i]=s2[lenb-1-i]-'0';
	for(int i=0;i<MAX;i++){
		c[i]=a[i]+b[i]+x;
		x=c[i]/10;
		c[i]%=10;
	} 
	if(x) c[MAX++]=x; 
	for(int i=MAX-1;i>=0;i--){
		cout<<c[i]; 
	} 
	return 0;
}

三.代码解析

Line1-3:导入头文件

Line4:命名空间

Line5-7:变量

Line9:读入两个数

Line10-11:分别计算长度

Line12:计算长的一个

Line13-14:倒序

Line15-19:一位一位计算

Line20:预留数位

Line21-23:倒序输出

相关推荐
Tim_109 分钟前
【LeetCode】338、比特位计数
c++·算法·leetcode
Brilliantwxx13 分钟前
【STM32】 SPI Flash 驱动开发实战:阻塞模式驱动 W25Q64(含工程代码)
开发语言·stm32·单片机·嵌入式硬件
wuyk55523 分钟前
【Socket 进阶之路】第 9 章 Linux 网络服务量产稳定性优化|心跳保活、TIME_WAIT、SO_LINGER、内存池、断线重连、完整异常防护框架
linux·服务器·开发语言·网络·物联网
木子算法23 分钟前
不是重心也不是中点:费马—韦伯点、它的最优性条件与迭代求解
人工智能·算法·目标跟踪
邪修king32 分钟前
Re:Linux 系统篇(三十四):进程间通信开篇Chapter1 —— 匿名管道 pipe 深度拆解与代码实战
android·linux·运维·开发语言
程序员AlbertTu1 小时前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算
孙启超1 小时前
【AI开发之Rust】第 13 课:async/await 与 tokio 异步运行时
开发语言·后端·rust
Am-Chestnuts1 小时前
DeepSeek内容转Word有哪几种方法?用DS随心转对比6条主流路径
开发语言·人工智能