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
Ideas
This question is very simple to do with a string type. Simply insert the read string from the last third digit into the comma "," (here the loop end condition must be written i> 0, not i> = 0, Otherwise, when the result is exactly six digits, the first digit will also be a comma (such as the case given in the example)), but here must be divided into positive and negative cases, if it is a negative number, first take the negative sign Come out, and then operate normally according to the previous positive method, and finally insert the negative sign back ~
Code
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main(){
int tmp1, tmp2;
cin>>tmp1>>tmp2;
int sum = tmp1+tmp2;
string result = to_string(sum);
if(result[0]=='-'){
string temp = result.substr(1,result.length()-1);
for(int i=temp.length()-3;i>0;i-=3) temp.insert(i,",");
result = temp;
result.insert(0,"-");
}
else{
for(int i=result.length()-3;i>0;i-=3) result.insert(i,",");
}
cout<<result;
return 0;
}