PAT甲级1001C++实现

题目:
1001 A+B Format (20 分)
Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).
Input Specification:
Each input file contains one test case. Each case contains a pair of integers a and b where −10
​6
​​≤a,b≤10
​6
​​. The numbers are separated by a space.
Output Specification:
For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.
Sample Input:
-1000000 9
Sample Output:
-999,991
思路:
计算两个整数之和,以标准形式输出,即每三位输出一个‘,’。因为要求的位数有限,可以使用取巧的方法,其结果最大值是7位数,只用考虑两个逗号。另外,结果的符号可以另外考虑,最后只要考虑整数的标准输出就可以了。没有采用取巧的方法,将计算结果转换为字符串。第一次计算的结果为不带逗号的字符串,第二次从后面遍历,每三个字符插入一个逗号。最后在将字符串输出就可以了。注意考虑三位数和六位数的情况,即防止数字开头出现逗号。
问题:
注意输出格式和数字的范围,本题不需要考虑int的范围。在写数数字转到字符串时没有考虑到0的情况,最后作特殊处理。
代码:

#include<iostream>
#include<string>
using namespace std;
int fang(int k) {
	int a = 1;
	for (int i = 0; i < k; ++i) {
		a = a * 10;
	}
	return a;
}
int main()
{
	int A, B;
	cin >> A >> B;
	int ru = A + B;
	string str;
	int falg = 0;
	for (int i = 7; i >= 0; --i) {
		if (ru < 0) {
			ru = -ru;
			cout << "-";
		}
		int num = 0;
		if (falg == 0)
		{
			if (ru - fang(i) >= 0) {
				falg = 1;
			}
		}
		if (falg == 1) {
			num = ru / fang(i);
			ru = ru - num*fang(i);
			char a = '0' + num;
			str = str + a;
		}
	}
	int count = 3;
	string b;
	for (int i = str.size() - 1; i >= 0; --i) {
		count--;
		b = b + str[i];
		if (count == 0 && i != 0) {
			count = 3;
			b = b + ',';
		}
	}
	if (b.empty()) {
		cout << "0";
	}
	else {
		for (int i = b.size() - 1; i >= 0; --i) {
			cout << b[i];
		}
	}
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值