fork(1) download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <vector>
  5.  
  6. std::vector<bool> to_binary(int num)
  7. {
  8. std::vector<bool> binary;
  9. while(num != 0)
  10. {
  11. binary.emplace_back(num % 2 != 0);
  12. num /= 2;
  13. }
  14. return binary;
  15. }
  16.  
  17. int findlargestGap(int num)
  18. {
  19. int largest_gap = 0;
  20. auto binary = to_binary(num);
  21. auto it = binary.begin();
  22. const auto it_end = binary.end();
  23. while(it != it_end)
  24. {
  25. auto current_true = std::find(it, it_end, true);
  26. if(current_true == it_end)
  27. break;
  28.  
  29. auto next_true = std::find(current_true+1, it_end, true);
  30. if(next_true == it_end)
  31. break;
  32.  
  33. const auto d = std::distance(current_true, next_true) - 1;
  34. largest_gap = std::max(largest_gap, static_cast<int>(d));
  35.  
  36. it = next_true;
  37. }
  38.  
  39. return largest_gap;
  40. }
  41.  
  42. int main(int argc, char** argv)
  43. {
  44. std::cout << "largest gap for 9: " << findlargestGap(9) << '\n';
  45. std::cout << "largest gap for 529: " << findlargestGap(529) << '\n';
  46. std::cout << "largest gap for 20: " << findlargestGap(20) << '\n';
  47. std::cout << "largest gap for 15: " << findlargestGap(15) << '\n';
  48. std::cout << "largest gap for 32: " << findlargestGap(32) << '\n';
  49. }
  50.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
largest gap for 9: 2
largest gap for 529: 4
largest gap for 20: 1
largest gap for 15: 0
largest gap for 32: 0