问题描述:
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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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
思路:先进行普通的A+B,将得到的结果转换成字符串处理,从后往前遍历加入一个空串,每隔插入一个逗号,注意最高位的数字前不要加逗号。
具体代码如下:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int a, b, s;
cin >> a >> b;
int c = a + b;
stringstream ss;
ss << c;
string t;
ss >> t;
if(t[0] == '-')
s = 1;
else
s = 0;
string str = "";
int k = 0;
for(int i = t.length() - 1; i >= s; i --) {
str = t[i] + str;
k ++;
if(k == 3 && i != s) {
str = ',' + str;
k = 0;
}
}
if(s == 1)
str = '-' + str;
cout << str << endl;
return 0;
}