【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 #include 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;}