日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1001 A+B Format (20分)——12行代码AC

發布時間:2024/2/28 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。