PAT甲级(1001:A+B Format)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT甲级(1001:A+B Format)相关的知识,希望对你有一定的参考价值。
参考技术A 计算a+b并以标准格式输出和——也就是说,数字必须用逗号分隔成三组(除非数字个数少于四位)。输入规格:
每个输入文件包含一个测试用例。每种情况都包含一对整数a和b,-1000000 <= a, b <= 1000000。其中这些数字用空格隔开。
输出规范:
对于每个测试用例,您应该在一行中输出a和b的和。总和必须用标准格式写。
样例输入:
-1000000 9
样例输出:
-999,991
题解:
把数字a+b的和转化成字符串,如果第一位是负号先跳过,只要当前位的下标i满足(i + 1) % 3等于字符串长度 % 3并且i不是最后一位,就在逐位输出的时候在该位输出后的后面加上一个逗号。
PAT 甲级 1001 A+B Format
https://pintia.cn/problem-sets/994805342720868352/problems/994805528788582400
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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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
代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 1e5 + 10; char s[maxn], out[maxn]; int a[maxn]; void zlr_itoa(int x) { if(x == 0) { s[0] = ‘0‘; s[1] = 0; return ; } int top = 0; while(x) { a[top ++] = x % 10; x = x / 10; } int sz = 0; while(top != 0) { s[sz++] = (char)(a[-- top] + ‘0‘); s[sz] = 0; } } int main() { int a, b; scanf("%d%d", &a, &b); int sum = a + b; if(sum == 0) { printf("0 "); return 0; } if(sum < 0) { printf("-"); sum = sum * (-1); } zlr_itoa(sum); int len = strlen(s); if(len < 3) { printf("%s ", s); return 0; } if(len % 3 == 0) { for(int i = 0; i < len - 3; i += 3) { for(int j = i; j < i + 3; j ++) printf("%c", s[j]); printf(","); } printf("%c%c%c", s[len-3], s[len - 2], s[len - 1]); } else if(len % 3 == 1) { printf("%c,", s[0]); for(int i = 1; i < len - 4; i += 3) { for(int j = i; j < i + 3; j ++) printf("%c", s[j]); printf(","); } printf("%c%c%c", s[len-3], s[len - 2], s[len - 1]); } else if(len % 3 == 2) { printf("%c%c,", s[0], s[1]); for(int i = 2; i < len - 5; i += 3) { for(int j = i; j < i + 3; j ++) printf("%c", s[j]); printf(","); } printf("%c%c%c", s[len-3], s[len - 2], s[len - 1]); } printf(" "); return 0; }
以上是关于PAT甲级(1001:A+B Format)的主要内容,如果未能解决你的问题,请参考以下文章