日期:2026年1月16日
ZeroJudge 題目連結:a741. 10101 - Bangla Numbers
解題想法
用自訂函式 convert,將輸入的整數 n 轉換成題目要的字串。先處理 $n = 0$ 的特例,直接回傳字串 0。如果 $n > 1000000000$,需要先處理這部分的係數,也就是 kuti 的數量。接下來再依序處理 lakh, hajar, shata 的數量。
Python 程式碼
使用時間約為 30 ms,記憶體約為 5.8 MB,通過測試。
import sys
def convert(n): # 輸入數字 n,輸出答案字串
if n == 0: return "0" # 特例,直接回傳 0
unit = (10000000, 100000, 1000, 100)
word = ("kuti", "lakh", "hajar", "shata")
result = [] # 儲存答案用的串列,內容為 [數量, 單位, ...]
if n > 1000000000: # 前面的位數可以再細分
left = n // 10000000 # 前面的位數,上限為 99999999
n %= 10000000 # 剩下的位數
for u, w in zip(unit, word):
r = left // u # 取這個單位對應的數量
if r > 0: result += [str(r), w] # r 大於 0,r 轉成字串,r, w 加到 result
left %= u # left 取餘數
if left > 0: result.append(str(left)) # 剩下的位數
result.append("kuti") # 前面整串代表 kuti 的數量
for u, w in zip(unit, word): # 由大到小讀取單位對應的數值、字串
r = n // u # 取這個單位對應的數量
if r > 0: result += [str(r), w] # r 大於 0,r 轉成字串,r, w 加到 result
n %= u # n 取餘數
if n > 0: result.append(str(n)) # 如果有小於 100 的值,加到 result
return " ".join(result) # 用空格接成字串再回傳
result = []
lines = sys.stdin.readlines() # 讀取所有測資
idx = 0
while idx < len(lines):
n = int(lines[idx])
idx += 1
result.append(f"{idx:3d}. {convert(n):s}\n")
sys.stdout.write("".join(result))
C++ 程式碼
使用時間約為 7 ms,記憶體約為 340 kB,通過測試。
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
typedef long long LL;
using namespace std;
void convert(LL n) { // 輸入數字 n
if (n == 0) { // 特例,直接印出 0
cout << "0\n";
return;
}
int unit[4] = {10000000, 100000, 1000, 100};
string word[4] = {"kuti", "lakh", "hajar", "shata"};
vector<string> result; // 儲存答案用的串列,內容為 [數量, 單位, ...]
if (n > 1000000000) { // 前面的位數可以再細分
int left = n / 10000000; // 前面的位數,上限為 99999999
n %= 10000000; // 剩下的位數
for(int i=0; i<4; i++) {
int u = unit[i]; // 單位大小
string w = word[i]; // 單位字串
int r = left / u; // 取這個單位對應的數量
if (r > 0) { // r 大於 0
result.push_back(to_string(r)); // r 轉成字串加到 result
result.push_back(w); // w 加到 result
}
left %= u; // left 取餘數
}
if (left > 0) result.push_back(to_string(left)); // 剩下的位數
result.push_back("kuti"); // 前面整串代表 kuti 的數量
}
for(int i=0; i<4; i++) {
int u = unit[i]; // 單位大小
string w = word[i]; // 單位字串
int r = n / u; // 取這個單位對應的數量
if (r > 0) { // r 大於 0
result.push_back(to_string(r)); // r 轉成字串加到 result
result.push_back(w); // w 加到 result
}
n %= u; // n 取餘數
}
if (n > 0) result.push_back(to_string(n)); // 如果有小於 100 的值,加到 result
int m = (int)result.size(); // result 的長度
for(int i=0; i<m; i++) cout << result[i] << " \n"[i == m-1];
return;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
LL n;
int idx = 0;
while(cin >> n) {
idx++;
cout << setw(3) << idx << ". ";
convert(n);
}
return 0;
}
沒有留言:
張貼留言