PAT (Advanced Level) 1001 A+B Format (20 分)
发布日期:2021-06-29 12:22:11
浏览次数:3
分类:技术文章
本文共 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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月17日 20时13分03秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
插件机制+自定义axios(五)
2019-04-29
Redis的学习之路
2019-04-29
Windows下Redies+GUI安装,使用Jedis与spring boot 整合
2019-04-29
Windows创建本地版本库(1)
2019-04-29
基于java的酒店管理系统的设计与实现
2019-04-29
基于WEB的仓库管理系统的设计与实现
2019-04-29
基于java的web聊天系统
2019-04-29
基于java的俄罗斯方块的设计与实现
2019-04-29
基于java的魂斗罗的设计
2019-04-29
基于java的网页内容管理
2019-04-29
基于java的学生管理系统
2019-04-29
基于java网盘搜索的设计与实现
2019-04-29
基于SSM的仿小米商城源码
2019-04-29
基于SSM的医院人事管理系统的设计与实现
2019-04-29
基于SSM的网上购物系统的设计与开发
2019-04-29
基于SSM框架的BS微博系统的设计与实现
2019-04-29
超市订单管理系统
2019-04-29
基于ssm的民宿网站
2019-04-29
基于JavaWeb的物流管理系统的设计与实现
2019-04-29