被一道a+b题给卡住三个多小时,自己果然是个人才。

题目

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 -10^6<a,b<10^6. 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.

Simple Input:

-100000, 9

Simple Output:

-999,991

想法

这道题自己想了很久,一会想想是不是要用二维数组存, 一会想想是不是要给他倒过来、分割、然后再正过来、添逗号,想了三个多小时,最后,只能看题解,看到一位大佬用的是:

从后面开始添逗号,这样不会一边添着,一边改变数组的相对位置,最后变成每两个数字中间就添一个逗号的样子。

他还是想的很到位的,起码比我想得好。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string s = to_string(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;
}

我自己写的代码不知道为什么找不到了,先用网上大佬的代码摸鱼。

尾语

第一次用markdown文法写博客,第一次在自己博客上写题解,两件事重合在一起……白学家,拖出去枪毙五分钟。还是自己在自己的平台上写一些自己的东西,是比较令人开心的事情呢,希望自己今后更博速度快点,不要咕咕咕(求求你不要立flag好不好?)。

相关文章
评论
分享
Please check the post_relate setting in config.yml of hexo-theme-Annie! You should make sure 'postsEnable == true' and the number of site posts greater than 1.
Please check the comment setting in config.yml of hexo-theme-Annie!