日期:2025年6月26日
ZeroJudge 題目連結:a034. 二進位制轉換
解題想法
因為 Python 有內建整數轉成二進位字串的工具 bin,可以直接用 bin 解題。比較一般的作法是用 while 迴圈及位元運算,從個位數開始依序計算此位是 1 或 0,用字串儲存答案。
Python 程式碼
先用 int 將輸入字串 line 轉成整數,再用 bin 轉成2進位制,但是直接輸出時開頭會有 **0b**,所以再用 str 轉換成字串,只從索引值為2的位置開始輸出。使用時間約為 19 ms,記憶體約為 3.3 MB,通過測試。
使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
import sys
for line in sys.stdin:
print(str(bin(int(line)))[2:])
使用時間約為 18 ms,記憶體約為 3.3 MB,通過測試。
import sys
def convert(n):
s = ""
while n > 0:
s = str(n&1) + s
n >>= 1
return s
for line in sys.stdin:
print(convert(int(line)))
C++ 程式碼
使用時間約為 2 ms,記憶體約為 316 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;
string bin(int n) {
string s = "";
while(n > 0) {
s = char((n&1)+'0') + s;
n >>= 1;
}
return s;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n;
while(cin >> n) cout << bin(n) << "\n";
return 0;
}
沒有留言:
張貼留言