【c++】大整数加法模板

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/u011956367/article/details/97682782

思路:

大整数加法,采用字符串存储数据,只需模拟手工运算即可,需要注意的是两个加数得长度对其,不然不利于计算。不足补0。

样例输入:

1+2

33+5

样例输出:

3

38

代码:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void solve(string a,string b){//加法处理 
	int mmax=max(a.size(),b.size());//最大长度 
	while(a.size()<mmax) a="0"+a;//最大对齐 
	while(b.size()<mmax) b="0"+b;//最大对齐 
	string c="";//结果 
	int jin=0;//进位 
	for(int i=mmax-1;i>=0;i--){
		int wei=a[i]+b[i]-2*'0'+jin;//对应位加法结果 
		jin=wei/10;//进位值 
		wei%=10;//保留值 
		c=char('0'+wei)+c;
	}
	if(jin!=0) c=char('0'+jin)+c;//如果最终还需要进位 
	cout<<c<<endl;
}
int main(){
    string a,b;
    while(cin>>a){
    	b="";
	    int f=0;
	    for(f;a[f]!='+';f++);//分割字符串 
	    for(int i=1;f+i<a.size();i++){
	        b+=a[f+i];
	    }
	    a.erase(a.begin()+f,a.end());//删除a中+以后的部分 
	    solve(a,b);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u011956367/article/details/97682782
今日推荐