fork(4) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template<int N>
  5. struct lookup_table {
  6. int table[N];
  7.  
  8. constexpr int& operator[](size_t i) {
  9. return table[i];
  10. }
  11.  
  12. constexpr const int& operator[](size_t i) const {
  13. return table[i];
  14. }
  15. };
  16.  
  17. constexpr int bit_count(int i) {
  18. int bits = 0;
  19. while (i) { i &= i-1; ++bits; }
  20. return bits;
  21. }
  22.  
  23. template<int N>
  24. constexpr lookup_table<N> generate() {
  25. lookup_table<N> table = {};
  26.  
  27. for (int i = 0; i < N; ++i)
  28. table[i] = bit_count(i);
  29.  
  30. return table;
  31. }
  32.  
  33. template<int I> struct Check {
  34. Check() {
  35. std::cout << I << "\n";
  36. }
  37. };
  38.  
  39. constexpr auto table = generate<65536>();
  40.  
  41. int main() {
  42. // checks that they are evaluated at compile-time
  43. Check<table[5]>();
  44. Check<table[65535]>();
  45.  
  46. // test
  47. int i;
  48. while (cin >> i) {
  49. cout << table[i] << ' ';
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 15496KB
stdin
1 2 3 4 5 6 7 8 9 10 65535
stdout
2
16
1 1 2 1 2 2 3 1 2 2 16