C++实现大数加法运算

版权声明:晓程原创 https://blog.csdn.net/qq_43469554/article/details/88190984
#include <iostream>
#include <algorithm>
#include <string>
const int N = 1e6;
using namespace std;
char _a[N], _b[N];
string add(string a, string 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;
	//翻转, 便于从低位逐步求和
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	string ans(len, '0');
	for (int i = 0; i < lena; i++)
	{
		ans[i] = a[i];
	}
	int tmp = 0;
	for (int i = 0; i < len; i++)
	{
		if (i < b.length())
		{
			tmp += (ans[i] - '0') + (b[i] - '0');
		}
		else
		{
			tmp += (ans[i] - '0');
		}
		ans[i] = tmp % 10 + '0';
		tmp /= 10;
	}
	reverse(ans.begin(), ans.end());
	return ans.substr(ans.find_first_not_of('0'));
}

int main()
{
	string a = "1111";
	string b = "9999";
	cout << add(a, b) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/88190984