日期:2025年12月3日
ZeroJudge 題目連結:k645. 數學得力工具
解題想法
這題要先用 + 分割字串,取出字串中的數字,將數字由小到大排序,再將數字用 + 連接後輸出。如果用 Python 解題,可以用 split 分割字串,用 sorted 排序數字,用 join 連接字串,一行解。用 C++ 解題則會比較麻煩一點。
Python 程式碼
一行解,使用時間約為 40 ms,記憶體約為 3.3 MB,通過測試。
print("+".join(sorted(list(input().split("+")))))
C++ 程式碼
使用時間約為 3 ms,記憶體約為 380 kB,通過測試。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s, num = ""; getline(cin, s);
vector<string> eq;
for(char c : s) {
if (c == '+') {
eq.push_back(num);
num = "";
} else {
num += c;
}
}
eq.push_back(num);
sort(eq.begin(), eq.end());
for(int i=0; i<(int)eq.size(); i++) {
cout << eq[i] << "+\n"[i == (int)eq.size()-1];
}
return 0;
}
沒有留言:
張貼留言