#include <iostream> #include <vector> using namespace std; int bitsSetTable256[256]; // Function to initialise the lookup table void initialize() { bitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { bitsSetTable256[i] = (i & 1) + bitsSetTable256[i / 2]; } } int countBits(int i) { return (bitsSetTable256[i & 0xff] + bitsSetTable256[(i >> 8) & 0xff] + bitsSetTable256[(i >> 16) & 0xff] + bitsSetTable256[i >> 24]); } int main() { int n; scanf("%d", &n); initialize(); int sum = 0; int i = 1; std::vector<int> vec; while (sum < n) { sum += countBits(i); vec.push_back(i); i++; } int k = vec.size() - 2; int deletedElements = 0; while (sum > n) { int extraBits = countBits(vec[k]); if (sum - extraBits >= n) { sum -= extraBits; vec[k] = 0; deletedElements++; } k--; } printf("%lu\n", vec.size() - deletedElements); for(int j = vec.size() - 1; j >=0 ; j--) { if(vec[j] > 0) { printf("%d ", vec[j]); } } 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 51 52 53 54 55 | #include <iostream> #include <vector> using namespace std; int bitsSetTable256[256]; // Function to initialise the lookup table void initialize() { bitsSetTable256[0] = 0; for (int i = 0; i < 256; i++) { bitsSetTable256[i] = (i & 1) + bitsSetTable256[i / 2]; } } int countBits(int i) { return (bitsSetTable256[i & 0xff] + bitsSetTable256[(i >> 8) & 0xff] + bitsSetTable256[(i >> 16) & 0xff] + bitsSetTable256[i >> 24]); } int main() { int n; scanf("%d", &n); initialize(); int sum = 0; int i = 1; std::vector<int> vec; while (sum < n) { sum += countBits(i); vec.push_back(i); i++; } int k = vec.size() - 2; int deletedElements = 0; while (sum > n) { int extraBits = countBits(vec[k]); if (sum - extraBits >= n) { sum -= extraBits; vec[k] = 0; deletedElements++; } k--; } printf("%lu\n", vec.size() - deletedElements); for(int j = vec.size() - 1; j >=0 ; j--) { if(vec[j] > 0) { printf("%d ", vec[j]); } } return 0; } |