【PAT甲级】题解-1001 A+B Format

PAT :计算机程序设计能力考试:一个高校编程学习赛,内容基础,据说题目描述含糊不清,造成诸多理解错误。

第一观感是:输入输出样例极少,未给学生充分理解题目,提供更多辅助。

PAT 甲级:英文题目,涉及基础数据结构。【胡说,涉及好多算法】

问题描述

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).

计算 a+b 的和,结果按照以下格式输出:每三个数字使用一个 , 分割(除非结果不足三位数)。

输入格式

Each input file contains one test case. Each case contains a pair of integers a and b where −106 ≤a,b≤10 6. The numbers are separated by a space.

一行输入,包含两个整数 a 和 b(−106 ≤a,b≤10 6),数字之间使用空格分割。

输出格式

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.

按照指定格式输出 a 和 b 的和,仅一行。

输入输出样例

输入样例输出样例
-1000000 9-999,991

样例解释:无

题解 1

思路分析:若是和不足 4 位数,直接输出,否则取和的绝对值,按位拆分,每三个数字插入 ,,而后输出时,注意负号和首字符为 , 的情况。

#include <iostream>
#include <cmath>
using namespace std;

int main() {

	int a, b;
	cin >> a >> b;

	int n = a + b;
	
	if(n < 1000 && n > -1000) {
		cout << n << endl;
		return 0;
	}

	bool f = n < 0;	// 记录负号
	n = abs(n);		// 取和的绝对值

	char chs[20];
	int i = 0;		// 记录 chs 字符数
	int c = 1;		// 记录数字个数
	while(n) {		// 将和按位拆分,每三个数字,拆入一个 ','
		chs[i++] = n % 10;
		if(c % 3 == 0) chs[i++] = ',';
		n /= 10;
		c ++;
	}

	// 还原负号
	if(f) cout << '-';
	// 注意数字位数是 3 的倍数时,首字符是 ',',不做输出
	if(chs[i - 1] != ',') cout << int(chs[i - 1]);

	for(int j = i - 2; j >= 0; j--) {
		if(chs[j] == ',')
			cout << chs[j];
		else cout << int(chs[j]);
	}

	cout << endl;
	return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老坛算粉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值