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
核心思想是如何去处理字符串,我开始写的时候用int直接去处理,其实就偏离了题目的本意。本题的核心就是通过字符串处理,代码当时有两个点过不去,主要是因为没有判断到如果是最后一位是3的整除情况
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
string c = to_string(a + b);
string res;
for (int i = c.size() - 1, j = 0; i >= 0; i--) {
res = c[i] + res;
j++;
if (j % 3 == 0 and c[i - 1] != '-' and i)
res = ',' + res;
}
cout<<res<<endl;
return 0;
}
有些人问我 为啥没有string 头文件 其实iostream里面已经包含了