fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <limits>
  4. #include <type_traits>
  5.  
  6.  
  7. template <typename int_type,
  8. class = typename std::enable_if<std::is_unsigned<int_type>::value>::type>
  9. std::string to_binary(int_type num)
  10. {
  11. if (num == 0)
  12. return std::string(1, '0');
  13.  
  14. // begin with most significant bit:
  15. int_type mask = 1 << (std::numeric_limits<int_type>::digits - 1);
  16.  
  17. while (mask && !(mask&num)) // skip over leading 0s
  18. mask >>= 1;
  19.  
  20. std::string result;
  21. while (mask)
  22. {
  23. result += (mask & num) ? '1' : '0';
  24. mask >>= 1;
  25. }
  26.  
  27. return result;
  28. }
  29.  
  30. template <typename int_type,
  31. class = typename std::enable_if<std::is_unsigned<int_type>::value>::type>
  32. unsigned groups_of_1s(int_type num)
  33. {
  34. int_type mask = 1;
  35. bool in_group = false;
  36. unsigned count = 0;
  37.  
  38. while (mask)
  39. {
  40. if (mask & num)
  41. {
  42. if (!in_group)
  43. {
  44. in_group = true;
  45. ++count;
  46. }
  47. }
  48. else
  49. in_group = false;
  50.  
  51. mask <<= 1;
  52. }
  53.  
  54. return count;
  55. }
  56.  
  57. int main()
  58. {
  59. const unsigned value = 183;
  60. std::cout << value << ": " << to_binary(value) << ", " ;
  61. std::cout << groups_of_1s(value) << " groups of 1.\n";
  62. }
Success #stdin #stdout 0s 3472KB
stdin
Standard input is empty
stdout
183: 10110111, 3 groups of 1.