#include <iostream> using namespace std; int OnBitsAmount(int n) { int amount = 0; while (n) { amount += n & 1; n >>= 1; } return amount; } int main() { int n; cin >> n; int sum = 0; int skippedNum = 0; int maxOnesNum = 0; int startNum = 0; for (int i = 1; i <= n; i++) { sum += OnBitsAmount(i); maxOnesNum = max(OnBitsAmount(i), maxOnesNum); if (sum >= n) { startNum = i; break; } } if (sum >= n - maxOnesNum) { for (int j = startNum; j >= 1; j--) { if (OnBitsAmount(j) == sum - n) { skippedNum = j; goto end; } } } end: if (skippedNum != 0) { cout << startNum - 1 << endl; for (int i = startNum; i >= 1; i--) { if (i != skippedNum) cout << i << " "; } } else { cout << startNum << endl; for (int i = startNum; i >= 1; i--) cout << i << " "; } 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 50 | #include <iostream> using namespace std; int OnBitsAmount(int n) { int amount = 0; while (n) { amount += n & 1; n >>= 1; } return amount; } int main() { int n; cin >> n; int sum = 0; int skippedNum = 0; int maxOnesNum = 0; int startNum = 0; for (int i = 1; i <= n; i++) { sum += OnBitsAmount(i); maxOnesNum = max(OnBitsAmount(i), maxOnesNum); if (sum >= n) { startNum = i; break; } } if (sum >= n - maxOnesNum) { for (int j = startNum; j >= 1; j--) { if (OnBitsAmount(j) == sum - n) { skippedNum = j; goto end; } } } end: if (skippedNum != 0) { cout << startNum - 1 << endl; for (int i = startNum; i >= 1; i--) { if (i != skippedNum) cout << i << " "; } } else { cout << startNum << endl; for (int i = startNum; i >= 1; i--) cout << i << " "; } return 0; } |