題目原文:
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
Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space.
Output
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 9Sample Output
-999,991
題目意思:
輸入倆int型數字,對數字大小范圍有規定,計算和,並且按照標准格式輸出。標准格式為:從末尾數字開始數,每隔三個有一個","號,如果數字本來就不足四位,則前面不加","號。
題解:
計算倆數字和之後,轉換成string型,由於數字長度也不大,於是把數字給分解了,放到一個map裡,看代碼23和24行,比如最後一位就是m[1]="X",這樣再輸出的時候,如果m[i]的i值為3的倍數且小於str去除"-"號之後的長度,則加","輸出。
1 #include <iostream> 2 #include <map> 3 #include <strstream> 4 using namespace std; 5 map <int,string> m; 6 int main() 7 { 8 int a,b; 9 while(cin>>a>>b){ 10 int sum = a+b; 11 //把int型的sum轉換成string型的str 12 strstream ss; 13 string str; 14 ss << sum; 15 ss >> str; 16 int str_length = str.length(); 17 if(sum<0){ 18 str_length--; 19 //刪除str的-號 20 str.erase(0,1); 21 } 22 //把str逆向輸入到m[i]中,str最後一位是m[1] 23 for(int i=1; i<=str_length; i++){ 24 m[i]=str.at(str_length-i); 25 } 26 if(sum<0) cout<<"-"; 27 for(int i=str_length; i>=1; i--){ 28 if(i%3==0&&i<str_length) cout<<","<<m[i]; 29 else cout<<m[i]; 30 } 31 cout<<endl; 32 } 33 return 0; 34 }
代碼:https://git.oschina.net/firstmiki/PAT-Advanced-Level-Practise