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
Experiential Summing-up
把 a+b 转化为字符串,除第一位为负号时(特判),当 (数组下标+1)%3 == 总和位数%3 ,且遍历的此数不是最后一位时,输出“,”。
Accepted Code
1 /*单纯的笨办法*/ 2 #include<bits/stdc++.h> 3 using namespace std; 4 5 int main() 6 { 7 int a, b, sum; 8 cin >> a >> b; 9 sum = a + b; 10 if(sum < 0) 11 { 12 sum = -sum; 13 cout << "-" ; 14 } 15 if(sum == 0) 16 { 17 cout << 0; 18 return 0; 19 } 20 21 int count = 0, temp = sum, temp_t = sum;//count为sum的位数 22 while(temp_t != 0) 23 { 24 temp_t /= 10; 25 count ++; 26 } 27 28 int q[10], ct = count; 29 while(temp != 0) 30 { 31 int g = temp % 10; 32 q[count] = g; 33 temp /= 10; 34 count --; 35 } 36 37 if(sum < 100 && sum > -100) 38 { 39 for(int i = 1; i <= ct; i ++) 40 cout << q[i]; 41 return 0; 42 } 43 if(ct % 3 == 0) 44 { 45 int k = 0; 46 for(int i = 1; i <= ct; i ++) 47 { 48 if(k == 3) 49 { 50 cout << ","; 51 k = 0; 52 } 53 cout << q[i]; 54 k ++; 55 } 56 } 57 if(ct % 3 == 1) 58 { 59 cout << q[1] << ","; 60 int k = 0; 61 for(int i = 2; i <= ct; i ++) 62 { 63 if(k == 3) 64 { 65 cout << ","; 66 k = 0; 67 } 68 cout << q[i]; 69 k ++; 70 } 71 } 72 if(ct % 3 == 2) 73 { 74 cout << q[1] << q[2] << ","; 75 int k = 0; 76 for(int i = 3; i <= ct; i ++) 77 { 78 if(k == 3) 79 { 80 cout << ","; 81 k = 0; 82 } 83 cout << q[i]; 84 k ++; 85 } 86 } 87 88 return 0; 89 }
1 /*简单聪明的办法*/ 2 #include<bits/stdc++.h> 3 using namespace std; 4 5 int main() 6 { 7 int a, b; 8 cin >> a >> b; 9 string s = to_string(a + b); 10 int len = s.length(); 11 for(int i = 0; i < len; i ++) 12 { 13 cout << s[i]; 14 if(s[i] == '-') continue; 15 if((i + 1) % 3 == len % 3 && i != len - 1) 16 cout << ","; 17 } 18 return 0; 19 }
标签:case,PAT,cout,Format,int,sum,include,1001 From: https://www.cnblogs.com/marswithme/p/17133293.html