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
这道题就是计算两个数字相加,因为两个数字的长度都不大于10^6次方,所以用int类型不会溢出。
将计算结果转换成字符串更好处理,如果第一位是“-’则直接输出,将“-”删除掉。剩下的数据,只要每三位加一个“,”,拼接起来输出即可。
#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
int b;
cin>>a>>b;
string temp =to_string(a+b);
if(temp[0]=='-'){
cout<<'-';
temp.erase(0,1);
}
int z =0;
for(int i=temp.length()-1;i>=0;i--){
z++;
if(z%3==0&&i>0){
temp.insert(i,",");
}
}
cout<<temp;
}