PTA-1001——A+B Format
阿新 • • 發佈:2019-01-14
題目:
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){ 14count++; 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 }