C++大数相加

主要分为以下几个步骤:
初始化数组 -> 输入字符串,并逆序 -> 按位保存到数组里 -> 按位相加,并处理进位 -> 判断最高位是否为0, 并逆序输出

参考代码:

#include <iostream>
#include <string>
#include <vector>
#include <cctype>
#include <cmath>
#include <cstring>
#include <algorithm>

using namespace std;

#define MAX 100

int main()
{
	//初始化步骤
	int a[MAX] = { 0 };
	int b[MAX] = { 0 };
	int c[MAX + 1] = { 0 };

	//输入相加的字符串,然后逆序(一定要逆序)
	string temp_str1, temp_str2;
	cin >> temp_str1 >> temp_str2;
	int s1_size = temp_str1.size(), s2_size = temp_str2.size();
	reverse(temp_str1.begin(), temp_str1.end());
	reverse(temp_str2.begin(), temp_str2.end());

	//按位存放到数组里去
	for (auto i = 0; i < s1_size; i++)
		a[i] = temp_str1[i] - '0';
	for (auto i = 0; i < s2_size; i++)
		b[i] = temp_str2[i] - '0';

	//相加长度以最长的字符串来算,然后按位相加,并处理进位问题
	int len_max = max(s1_size, s2_size);
	for (auto i = 0; i < len_max; i++)
	{
		c[i] = a[i] + b[i];
		if (c[i] >= 10)
		{
			c[i] -= 10;
			c[i + 1] += 1;
		}
	}

	//判断最高位是否为0,然后逆序输出
	if (c[len_max] != 0) cout << c[len_max];
	for (auto i = 0; i < len_max; i++)
		cout << c[len_max - i - 1];
	cout << endl;

	return 0;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值