PAT甲级1001 A+B Format
【摘要】
PATA1001 A+B Format
PATA1001 A+B Format
Calculate a+b and output the sum in standard format – tha...
PATA1001 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)
Sample Input:
-1000000 9
Sample Output:
-999,991
主要的工作是对输出的结果进行处理,怎么样使得逗号正确的分隔是关键。
我们可以使用 to string
将 A+B
的数字结果转化为字符串。
按照题意去用逗号分隔字符串。
to_string
的用法:to_string, 推荐查阅官方文档,表述清晰
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string s = to_string(a + b); //将输入的a+b的结果转化为字符串
//接下来我们处理字符串就可以了
int len = s.length();//计算字符串长度
for (int i = 0; i < len; i++) {
cout << s[i];
if (s[i] == '-')
continue;
if ((i + 1) % 3 == len % 3 && i != len - 1)
//判断是否需要加逗号
cout << ",";
}
return 0;
}c
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
if ((i + 1) % 3 == len % 3 && i != len - 1)
cout << ",";
- 1
- 2
上面这段可能不好理解,接下来我试着解释清楚
我们用 len % 3
将这个字符串里的字符分为 3
个一组。这个余数的数值代表着三个一组多出来了几个。我们从右边往左边 3 个一组开始分。分到最左边,要么刚刚好,要么多了1个或者两个。
- 如果刚刚好,那么第一个逗号的位置应该是,字符串从左往右数,第
**3**
个数值后面,也就是字符串下标为2
的位置,后面的逗号位置就是前一个逗号位置往后推3
个。 - 如果余
1
,那么第一个逗号的位置应该是,字符串从左往右数,第**1**
个数值后面,也就是字符串下标为0
的位置,后面的逗号位置就是前一个逗号位置往后推3
个。 - 如果余
2
,那么第一个逗号的位置应该是,字符串从左往右数,第**2**
个数值后面,也就是字符串下标为1
的位置,后面的逗号位置就是前一个逗号位置往后推3
个。
这样判断条件 (i + 1) % 3 == len % 3
就出来了。
然而,字符串末尾肯定是不能加逗号的。
所以我们要加上一句 i != len - 1
文章来源: blog.csdn.net,作者:沧夜2021,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/CANGYE0504/article/details/88827524
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)