牛客网————客官这边请(高精度问题,可以AC)

最近再练习高精度问题,这个题目是这样的:

这是一道典型的大数问题,可以看到我们要求两个大数相加的结果,大数相加原理可以看这里:https://blog.csdn.net/qq_41938259/article/details/104638833

只要稍加修改,主要是格式正确即可,代码如下:

#include<iostream>
#include<stack>
#include<sstream>
#include<cstring>
#include<string>
using namespace std;

void show(stack<int> a)
{
	while (!a.empty())
	{
		cout << a.top();
		a.pop();
	}
	return;
}

//a+b
stack<int> plusfunc(stack<int> a, stack<int> b)
{
	stack<int> aa, bb;
	while (!a.empty())
	{
		int temp = a.top();
		a.pop();
		aa.push(temp);
	}
	while (!b.empty())
	{
		int temp = b.top();
		b.pop();
		bb.push(temp);
	}

	stack<int> c;
	int carry = 0;
	while (!aa.empty() || !bb.empty())
	{
		if (!aa.empty() && !bb.empty())
		{
			int temp = aa.top() + bb.top() + carry;
			c.push(temp % 10);
			aa.pop(); bb.pop();
			carry = temp / 10;
		}
		else if (aa.empty())
		{
			int temp = bb.top() + carry;
			c.push(temp % 10);
			bb.pop();
			carry = temp / 10;
		}
		else if (bb.empty())
		{
			int temp = aa.top() + carry;
			c.push(temp % 10);
			aa.pop();
			carry = temp / 10;
		}
	}
	if (carry != 0)c.push(carry);
	return c;
}


int main(void)
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		stack<int> A, B;
		string a, b;
		cin >> a >> b;
		for (int i = a.size() - 1; i >= 0; i--)
			A.push(a[i] - '0');
		for (int i = b.size() - 1; i >= 0; i--)
			B.push(b[i] - '0');
		stack<int> result;
		result = plusfunc(A, B);
		cout << "Case " << i + 1 << ':' << endl;
		cout <<a<< " + ";
		cout <<b<< " = ";
		show(result);
		cout << endl;
        if(i!=n-1)
		    cout << endl;
	}


	system("pause");
	return 0;
}
发布了162 篇原创文章 · 获赞 38 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41938259/article/details/104709578