PAT甲级1001-1010

版权声明:转载请注明出处,谢谢! https://blog.csdn.net/qq_36095512/article/details/79419125

1001 A+B Format

注意stack的使用和将字符串转化为string的函数

#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(int argc, char*argv[])
{
	int A, B;
	cin >> A >> B;
	char st[10];
	sprintf(st, "%d", A+B);
	string str(st);
	stack<string>out;
	if (str[0] == '-')
	{
		cout << str[0];
		str.erase(0,1);
	}
	if (str.size() < 4)
		cout << str;
	else {
		while (str.size() > 3)
		{
			out.push(str.substr(str.size() - 3, 3));
			str.erase(str.size() - 3, 3);
			out.push(",");
		}
		out.push(str);
		while (!out.empty())
		{
			cout << out.top();
			out.pop();
		}
	}
	return 0;
}

1002 A+B for Polynomials

第二个测试点未通过,注意会出现两个系数相加为零的情况

注意输入输出使用scanf和printf,

#include<iostream>
#include<vector>
struct po {
	int ex;
	double cof;
};
using namespace std;
int main(int argc, char*argv[])
{
	int term1,term2,term(0);
	int temp(0);
	cin >> term1;
	vector<po>po1(term1);
	for (int i = 0; i < term1; i++)
		//cin >> po1[i].ex >> po1[i].cof;
		scanf("%d %lf ", &po1[i].ex, &po1[i].cof);
	cin >> term2;
	vector<po>po2(term2);
	for (int i = 0; i < term2; i++)
		scanf("%d %lf ", &po2[i].ex, &po2[i].cof);
		//cin >> po2[i].ex >> po2[i].cof;
	vector<po>out;
	int ind1(0), ind2(0);
	while (ind1 < po1.size() && ind2 < po2.size())
	{
		if (po1[ind1].ex < po2[ind2].ex)
		{
			out.push_back(po2[ind2]);
			ind2++;
		}
		else if (po1[ind1].ex < po2[ind2].ex)
		{
			out.push_back(po1[ind1]);
			ind1++;
		}
		else
		{
			if (po1[ind1].cof + po2[ind2].cof == 0)
			{
				ind1++;
				ind2++;
				continue;
			}
			out.push_back(po{ po1[ind1].ex,po1[ind1].cof + po2[ind2].cof });
			ind1++;
			ind2++;
		}
	}
	if(ind1==po1.size())
		while (ind2 < po2.size())
		{
			out.push_back(po2[ind2]);
			ind2++;
		}
	if(ind2==po2.size())
		while (ind1 < po1.size())
		{
			out.push_back(po1[ind1]);
			ind1++;
		}
	cout << out.size();
	for (auto i : out)
		printf(" %d %.1lf", i.ex, i.cof);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_36095512/article/details/79419125
今日推荐