日期:2025年8月5日
ZeroJudge 題目連結:b877. 我是電視迷
解題想法
這題可以用 if 判斷頻道號碼是否已經超過上限,從最前面繞回來;也可以取餘數找下一個頻道號碼。
Python 程式碼
使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
a, b = map(int, input().split())
if b > a: print(b-a)
else: print(100-a+b)
將第2、3行合併。使用時間約為 17 ms,記憶體約為 3.3 MB,通過測試。
a, b = map(int, input().split())
print(b-a if b > a else 100-a+b)
取餘數,因為 Python 的取餘數若遇到被除數是負值,會先將被除數加上除數之後再取餘數,餘數和除數同號,不需要像 C++ 要在程式碼中自己加上除數量值。使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
a, b = map(int, input().split())
print((b-a)%100)
C++ 程式碼
使用時間約為 2 ms,記憶體約為 312 kB,通過測試。
#include <iostream>
using namespace std;
int main() {
int a, b; cin >> a >> b;
if (b > a) cout << b-a << "\n";
else cout << 100-a+b << "\n";
return 0;
}
使用時間約為 2 ms,記憶體約為 320 kB,通過測試。
#include <iostream>
using namespace std;
int main() {
int a, b; cin >> a >> b;
cout << (b>a ? b-a : 100-a+b) << "\n";
return 0;
}
使用時間約為 2 ms,記憶體約為 316 kB,通過測試。
#include <iostream>
using namespace std;
int main() {
int a, b; cin >> a >> b;
cout << ((b-a)+100)%100 << "\n";
return 0;
}
使用時間約為 2 ms,記憶體約為 78 kB,通過測試。
#include <cstdio>
using namespace std;
int main() {
int a, b; scanf("%d %d", &a, &b);
printf("%d\n", ((b-a)+100)%100);
return 0;
}
沒有留言:
張貼留言