PTA (Advanced Level) 1001 A+B Format

1001 A+B Format

  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 −. 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

题目解析

       本题给出两个正整数,要求将其和由最后一位的数字开始每隔三位加一个,但是首尾与负数的符号后第一位都不可以有,

       可以使用头文件string中的to_string()函数将两数加和转化为字符串。

       将其反转,反转后首位便是和的最后一位,遍历反转后字符串,将其加入ans,每隔3位向ans中添加一位 , 对末位与符号前位进行特判即可。

复制代码
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int main()
 4 {
 5     int a, b;
 6     scanf("%d%d", &a, &b);  //输入a b
 7     string str = to_string(a + b);
 8     //将a与b的和转换为字符串储存在str中
 9     int cnt = 1;
10     string ans = "";
11     //ans记录最终答案
12     reverse(str.begin(),str.end());
13     //由于要从最后一个数字开始每隔三个数字添加一个 ,
14     //将str反转
15     for(auto i : str){
16         ans += i;
17         //每隔3个数字添加一个 , 最后一个位置与-前的位置不能添加 ,
18         if(cnt % 3 == 0 && cnt != str.size() && !(cnt == str.size() - 1 && str[str.size() - 1] == '-'))
19             ans += ',';
20         cnt++;
21     }
22     reverse(ans.begin(),ans.end());
23     cout << ans << endl;
24     return 0;
25 }
复制代码

 

posted @   suvvm  阅读(417)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(4)
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 2025成都.NET开发者Connect圆满结束
点击右上角即可分享
微信分享提示