a034. 二進位制轉換 5/16/2025

※ 注意正常情況需要對 0 做特判,但是測資沒有 0
(既然測資沒有,那麼我也得偷懶一下)


解法一、取餘數 (未優化)

num % 2 能夠取得 num 的最低位二進位數字 (0 或 1)
num 不斷除以 2,直到 num 變成 0

✅ 完整代碼

評分結果(參考) : AC (2ms, 332KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int num;
    while(cin >> num){
        string s;
        while(num != 0){
            s = (char)(num%2 + '0') + s;
            num /= 2;    
        }
        cout << s << "\n";
    }
    
    return 0;
}

解法二、取餘數 (優化後)

🔹 運算優化

num % 2 優化 (num & 1)
num / 2 優化 (num >>= 1)

🔹 字串加法優化

s = c + s; 每次需要複製一份 s,再用 c 加上他
複製的過程是 O(s.length)O(s.length)
如果有 n 個字元 c 那麼時間複雜度是 O(N2)O(N^{2})

s += c; 每次只要在 s 後面加上 c
這個過程是 O(1)O(1)
全部加完後反轉字串
如果有 n 個字元 c 那麼時間複雜度是 O(N)O(N)

✅ 完整代碼

評分結果(參考) : AC (2ms, 324KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int num;
    while(cin >> num){
        string s;
        while(num != 0){
            s += (char)((num&1) + '0');
            num >>= 1;
        }
        reverse(s.begin(), s.end());
        cout << s << "\n";
    }
    
    return 0;
}

解法三、bitset

✅ 完整代碼

評分結果(參考) : AC (2ms, 332KB)

#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int num;
    while(cin >> num){
        bitset<31> b(num);

        bool ignore0 = true;
        for(int i=31; i>=0; i--){
            if(b[i] || i==0) ignore0 = false;
            if(!ignore0) cout << b[i];
        }
        cout << "\n";
    }
    
    return 0;
}