ZJANS

d471. 0 與 1 的遊戲

Easy Last Update: 2026/01/30
進制轉換遞迴

給一個數字 n
輸出所有 n 個 bit 所能表示的 2 進位數字


解法一

✅ 完整代碼

評分結果(參考) : AC (1ms, 316KB)

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

int n;
string s;

void f(int k){
   if(k == n){
       cout << s << "\n";
       return;
   }
   
   s[k] = '0'; f(k+1);
   s[k] = '1'; f(k+1);
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    while(cin >> n){
        s.resize(n);
        f(0);
    }
    
    return 0;
}

解法二

✅ 完整代碼

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

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

int n;

string i2s(int num){
    string s;
    for(int i=0; i<n; i++){
        s += (num&1)+'0';
        num >>= 1;
    }
    reverse(s.begin(), s.end());
    return s;
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    while(cin >> n){
        for(int i=0; i<(1<<n); i++){
            cout << i2s(i) << "\n";
        }    
    }
    
    return 0;
}