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 −106≤a,b≤106. 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反转后即为所求//从后到前加,#includeusing 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月12日 17时36分20秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Linux下EasyPanel版本安装及升级
2019-04-29
raspberry pi(树莓派) + easycap d60 视频采集
2019-04-29
WebRTC
2019-04-29
rfc5766-turn-server NAT
2019-04-29
webrtc详细教程
2019-04-29
Android IOS WebRTC 音视频开发总结
2019-04-29
报表图表样式
2019-04-29
android模板图例
2019-04-29
树莓派网线直连
2019-04-29
复合材料培训(I第七期)
2019-04-29
复合材料生活中的应用
2019-04-29
ABAQUS复合材料(适合小白)
2019-04-29
ABAQUS高级案例解析
2019-04-29
人工智能药物研发
2019-04-29
【超级干货+福利】AIDD最全面的学习教程
2019-04-29
最新通知:AIDD与网络药理学资料大全
2019-04-29
Lammps分子动力学与第一性原理材料模拟及催化
2019-04-29
实习生小白的日常
2019-04-29
实习小白的日常(4)
2019-04-29