1001 A+B Format (20分)——12行代码AC
立志用最少的代碼做最高效的表達
PAT甲級最優題解——>傳送門
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 ?10^?6≤a,b≤10^?6. 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
技巧:
直接判斷后輸出負號,字符串存儲絕對值,方便統一計算。
代碼一:正序處理
利用取余確定循環初值,然后再按3的倍數輸出字符串和逗號
#include<bits/stdc++.h> using namespace std; int main( ) {int a, b; cin >> a >> b;if(a + b < 0) putchar('-');string s = to_string(abs(a+b));int i = s.size()%3 == 0 ? 3 : s.size()%3;cout << s.substr(0, i);for(; i < s.size(); i += 3) cout << ',' << s.substr(i, 3);return 0; }代碼二:倒序處理
字符串倒置,按3的倍數輸出逗號和字符串即可。
#include<bits/stdc++.h> using namespace std; int main() {int a, b; cin >> a >> b;if(a + b < 0) cout << '-';string s = to_string(abs(a+b));vector<string>v;for(int i = s.size(); i > 0; i -= 3) v.push_back(i>=3 ? s.substr(i-3, 3) : s.substr(0, i));for(int i = v.size()-1; i >= 0; --i)printf("%s%s", v[i].c_str(), i>0?",":""); }耗時
總結
以上是生活随笔為你收集整理的1001 A+B Format (20分)——12行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【简便解法】1035 插入与归并 (25
- 下一篇: 1002 A+B for Polynom