PAT (Advanced Level) 1001 A+B Format (20 分)
发布日期:2021-06-29 12:22:11 浏览次数:2 分类:技术文章

本文共 1187 字,大约阅读时间需要 3 分钟。

序:

这是一道关于字符串处理的题。

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

题目概述:

把两数相加后的结果按照从后到前三位一个逗号的格式输出。

分析:

1.将int转为string方便处理
2.将原结果的str1从后往前遍历,每三个数位加一个’,’(注意首位不加),并将该结果写入str2
3.str2反转后即为所求

//从后到前加,#include
using namespace std;int main(){
int a, b; scanf("%d%d", &a, &b); int sum = a + b; if(sum < 0) printf("-"); string str1 = to_string(abs(sum)); string str2; for(int i = 0; i < str1.size(); i++) {
str2 += str1[str1.size() - 1 - i]; if((i + 1) % 3 == 0 && i != str1.size() - 1) str2 += ','; } reverse(str2.begin(),str2.end()); printf("%s", str2.c_str()); printf("\n"); return 0;}

总结:

这道题一开始debug了半天,通过测试样例发现原来我写的逗号是从前往后加的,直接傻了。。。所以,还是想清楚题目要求再编码!

转载地址:https://bridge-killer.blog.csdn.net/article/details/115254002 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:PAT (Advanced Level) 1002 A+B for Polynomials (25 分)
下一篇:PAT甲级刷完一次的纪念日

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月12日 17时36分20秒