题目描述:
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
问题分析:
题目很简单,求a+b的和,然后按指定格式输出。根据样例分析,从后往前每3个字符前需要添加一个’,’。根据规律可以得出思路,将和转换为字符串,逆序每数三个字符,即添加一个’,’。不妨先使用vector存储结果。这里需要注意的是,每三个字符添加一个’,’,若a+b结果是3/6/9……位,则’,'岂不是会被添加到首位?因此需要特殊判断,避免出现这种情况。
代码示例:
#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
string toString(int a){
stringstream s;
s << a;
return s.str();
}
int main(){
int a, b, sum, count = 1;
cin >> a >> b;
sum = a+b;
if(sum < 0){//负数情况处理
cout << "-";
sum = -sum;
}
string str = toString(sum);
vector<char> chr;
for(int i = str.size()-1; i >= 0; i--, ++count){
chr.push_back(str[i]);
if(count % 3 == 0 && count < str.size())
chr.push_back(',');
}
for(int i = chr.size()-1; i >= 0; i--){//逆序打印
cout << chr[i];
}
return 0;
}