日期:2026年1月28日
ZeroJudge 題目連結:c014. 10035 - Primary Arithmetic
解題想法
這題只要依照直式加法的作法,從最後一位開始相加,如果最後一個分別為 a, b,目前的進位值為 carry,如果 $a + b + carry \geq 10$ 需要進位,進位次數 $cnt$ 加 1,同時 $carry$ 重設為 1;反之不需要進位,$carry$ 重設為 0。因為測資的數字在 10 位數以內,可以直接用整數處理就好;但如果數字很大,需要用字串格式才能處理。
Python 程式碼
整數格式,使用時間約為 22 ms,記憶體約為 2.9 MB,通過測試。
import sys
for line in sys.stdin:
n, m = map(int, line.split())
if n == 0 and m == 0: break
cnt, carry = 0, 0
while n > 0 or m > 0:
a, b = n%10, m%10
if a + b + carry >= 10:
cnt += 1
carry = 1
else:
carry = 0
n //= 10
m //= 10
if cnt == 0:
print("No carry operation.")
elif cnt == 1:
print("1 carry operation.")
else:
print(f"{cnt:d} carry operations.")
字串格式,使用時間約為 25 ms,記憶體約為 2.9 MB,通過測試。
import sys
for line in sys.stdin:
s, t = line.split()
if s == "0" and t == "0": break
n, m = len(s), len(t) # 長度
# 前面補 0 讓 s, t 長度相等
if n < m:
s = s.zfill(m)
else:
t = t.zfill(n)
# 由後往前計算加法及進位
cnt, carry = 0, 0 # 進位次數,目前進位的值
for a, b in zip(s[::-1], t[::-1]):
if int(a) + int(b) + carry >= 10:
cnt += 1
carry = 1
else:
carry = 0
# 輸出對應的答案
if cnt == 0:
print("No carry operation.")
elif cnt == 1:
print("1 carry operation.")
else:
print(f"{cnt:d} carry operations.")
C++ 程式碼
整數格式,使用時間約為 2 ms,記憶體約為 44 kB,通過測試。
#include <cstdio>
int main() {
int n, m;
while(scanf("%d %d", &n, &m) != EOF) {
if (n == 0 && m == 0) break;
int cnt = 0, carry = 0;
while(n > 0 || m > 0) {
int a = n%10, b = m%10;
if (a + b + carry >= 10) {
cnt++;
carry = 1;
} else {
carry = 0;
}
n /= 10; m /= 10;
}
if (cnt == 0) puts("No carry operation.");
else if (cnt == 1) puts("1 carry operation.");
else printf("%d carry operations.\n", cnt);
}
return 0;
}
字串格式,使用時間約為 2 ms,記憶體約為 324 kB,通過測試。
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s, t;
while(cin >> s >> t && (s != "0" || t != "0")) {
// 前面補 0 讓 s, t 長度相等
size_t n = s.size(), m = t.size();
if (n < m) {
while(s.size() < m) {
s = "0" + s;
}
} else {
while(t.size() < n) {
t = "0" + t;
}
}
// 由後往前計算加法及進位
int cnt = 0, carry = 0;
for(int i=(int)s.size()-1; i>=0; i--) {
int a = s[i] - '0', b = t[i] - '0';
if (a + b + carry >= 10) {
cnt++;
carry = 1;
} else {
carry = 0;
}
}
// 輸出對應的答案
if (cnt == 0) {
cout << "No carry operation.\n";
} else if (cnt == 1) {
cout << "1 carry operation.\n";
} else {
cout << cnt << " carry operations.\n";
}
}
return 0;
}
沒有留言:
張貼留言