A1001 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 −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
思考
将求和问题用字符串进行表示和处理是一种常规做法
即用 to_String(int) 进行转换
这一道题的关键在于 何时插入‘,’ 即从前往后输出 而又重后往前数数
((i + 1) % 3 == len % 3 && i != len - 1)
用取余比对的方法来解决这个问题 即通过总长度得出余数 并且保证最后一位不会多输出
代码示例
#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;
}
(解题时参考了柳婼大大的代码 有兴趣可以去看一下 -> 柳婼のBlog)
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!