給一個數字 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;
}