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
#include <iostream>
#include <vector>

unsigned long countBits(unsigned long number) {
	unsigned long count{};
	while (number > 0) {
		if (number & 1 != 0) {
			count++;
		}
		number >>= 1;
	}
	return count;
}

int main() {
	unsigned long expectedSum{};
	std::cin >> expectedSum;
	unsigned long sum{};
	std::vector<unsigned long> numbers;
	unsigned long i{1};
	while (sum < expectedSum) {
		numbers.push_back(i);
		sum += countBits(i);
		i++;
	}
	long pos = numbers.size() - 2;
	while (sum > expectedSum) {
		unsigned long difference = sum - expectedSum;
		const unsigned long numberOfBits = countBits(numbers[pos]);
		if (numberOfBits <= difference) {
			numbers.erase(numbers.begin() + pos);
			sum -= numberOfBits;
		}
		pos--;
	}
	std::cout << numbers.size() << std::endl;
	for (long i = numbers.size() - 1; i >= 0; i--) {
		std::cout << numbers[i];
		if (i > 0) {
			std::cout << " ";
		}
	}
	std::cout << std::endl;	

	return 0;
}