题目:
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 −. 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问题,两个注意点:
(1)在考虑逗号的时候,是每遇到3个数字加一个逗号,但最后一个逗号不一定存在,如600000,如果不把最后的逗号去掉,就会成为,600,000
(2)考虑a+b=0的情况,如果是0,字符串为空,这时要处理一下。
代码如下:
1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 int main(){ 6 int a,b; 7 cin>>a>>b; 8 int c = a+b; 9 int cc = c; 10 c = abs(c); 11 string s = ""; 12 int count = 0; 13 while(c){ 14 count++; 15 s += ('0'+c%10); 16 c /= 10; 17 if(count%3==0&&c){ //防止最后一位多出逗号,如600000,出现“,600,000”的情况 18 s += ','; 19 } 20 } 21 if(cc<0){ 22 s += '-'; 23 } 24 reverse(s.begin(),s.end()); 25 if(s == ""){ //注意判断和为0的情况,否则输出的s为空 26 cout<<0<<endl; 27 } else{ 28 cout<<s<<endl; 29 } 30 return 0; 31 }