C++之STL的string容器完成高精度的加法运算(装逼学法)

#include<algorithm>
#include<string>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
int main()
{
	int temp = 0;
	string a, b;
	cin >> a >> b;
	a = a.substr(a.find_first_not_of("0"));
	b = b.substr(b.find_first_not_of("0"));
	long long  lenA = a.length();
	long long  lenB = b.length();
	long long len = max(lenA,lenB) + 10;
	string answer(len,'0');
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	//把a拷贝到answer中
	for (int i = 0; i < lenA; i++)
	{
		answer.at(i) = a.at(i);//把字符串a复制给字符串answer
	}
	for (int i = 0; i < lenB; i++)//开始a+b
	{
		temp += (answer.at(i) - '0') + (b.at(i) - '0');
		answer.at(i) = temp % 10 + '0';
		temp = temp / 10;
	}
	if (temp == 1)//这里很特殊 我们要考虑是否temp==1(就是是否进位)
	{
		answer.at(lenB) += 1;
	}
	reverse(answer.begin(), answer.end());
	answer = answer.substr(answer.find_first_not_of("0"));
	cout << answer;
	return 0;
}

少年,让我们好好的去理解这个代码的整个过程吧
a.substr(a.find_first_not_of(“0”));//这行代码的意思是我们要将字符串中前面的’0‘给去掉 。 列入a的字符串是“000000123456789”,通过这段代码,我可以将a这个字符串变成“123456789” 说白了就是防止非法数据。为何要这里说呢,就是为了让你们更好的理解
answer = answer.substr(answer.find_first_not_of(“0”));这段代码

reverse();这个函数的作用是为了将字符串的顺序个反过来。
例子:
string c(“12345”);
reverse(c.begin(),c.end());
cout<<c;
这个时候的c是等于“45321”;

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值