#include <iostream> #include <unordered_set> using namespace std; int count_bits(int n) { int bits = 0; while (n > 0) { if (n % 2 == 1) { bits++; } n >>= 1; } return bits; } int main() { int n; cin >> n; int i = 1; int bits = 0; while (bits < n) { bits += count_bits(i++); } i--; unordered_set<int> ignore; for (int j = i; j > 0 && bits > n; j--) { int j_bits = count_bits(j); if (bits - j_bits >= n) { bits -= j_bits; ignore.insert(j); } } cout << (i - ignore.size()) << endl; for (int j = i; j > 0; j--) { if (ignore.count(j) == 0) { cout << j << " "; } } cout << endl; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include <iostream> #include <unordered_set> using namespace std; int count_bits(int n) { int bits = 0; while (n > 0) { if (n % 2 == 1) { bits++; } n >>= 1; } return bits; } int main() { int n; cin >> n; int i = 1; int bits = 0; while (bits < n) { bits += count_bits(i++); } i--; unordered_set<int> ignore; for (int j = i; j > 0 && bits > n; j--) { int j_bits = count_bits(j); if (bits - j_bits >= n) { bits -= j_bits; ignore.insert(j); } } cout << (i - ignore.size()) << endl; for (int j = i; j > 0; j--) { if (ignore.count(j) == 0) { cout << j << " "; } } cout << endl; return 0; } |