PAT甲级——A1001A+BFormat

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

很简单,数字转字符串即可
复制代码
 1 #define _CRT_SECURE_NO_WARNINGS
 2 
 3 #include <iostream>
 4 #include <vector>
 5 #include <sstream>
 6 #include <string>
 7 #include <stack>
 8 
 9 using namespace std;
10 
11 int main()
12 {
13     int a, b,sum;
14     string str;
15     scanf("%d %d", &a, &b);
16     sum = a + b;
17     stringstream ss;
18     ss << sum;
19     ss >> str;
20 
21     ///此处可以通过sum/1000,然后转为字符串
22     stack<string>res;
23     int k;
24     string s;
25     for (k = str.length(); k > 3;k-=3)
26     {    
27         s.assign(str.begin() + k - 3, str.begin() + k);
28         res.push(s);
29         res.push(",");
30     }
31     s.assign(str.begin(), str.begin() + k);
32     if (s == "-")
33         res.pop();
34     res.push(s);
35     while (!res.empty())
36     {
37         cout << res.top();
38         res.pop();
39     }
40     return 0;
41 }
复制代码

更简洁点

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 int main() {
 4     int a, b;
 5     cin >> a >> b;
 6     string s = to_string(a + b);
 7     int len = s.length();
 8     for (int i = 0; i < len; i++) {
 9         cout << s[i];
10         if (s[i] == '-') continue;
11         if ((i + 1) % 3 == len % 3 && i != len - 1) cout << ",";
12     }
13     return 0;
14 }
复制代码

 

posted @   自由之翼Az  阅读(199)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
点击右上角即可分享
微信分享提示