fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. bool isClap(int digit) {
  5. return digit == 3 || digit == 6 || digit == 9;
  6. }
  7.  
  8. // Input validation
  9. bool checkInput(long long& a, long long& b) {
  10. // Read two integers from input
  11. if (!(std::cin >> a >> b))
  12. return false;
  13.  
  14. std::cin >> std::ws;
  15. char c;
  16. // Check for extra characters (must be newline)
  17. if (std::cin.get(c) && c != '\n')
  18. return false;
  19.  
  20. return (a >= 1 && b <= 100000000 && a <= b);
  21. }
  22.  
  23. // Count occurrences of 3, 6, 9 in numbers from 1 to n
  24. long long countClaps(long long n) {
  25. std::string S = std::to_string(n);
  26. int lengthOfNumber = S.size();
  27. long long count = 0;
  28. long long right_multiplier = 1;
  29.  
  30. for (int pos = lengthOfNumber - 1; pos >= 0; --pos) {
  31. int currentNumber = S[pos] - '0';
  32.  
  33. // Get number formed by digits to the left of current position
  34. long long leftValue = (pos == 0) ? 0 : std::stoll(S.substr(0, pos));
  35. // Get number formed by digits to the right of current position
  36. long long rightValue = (pos == lengthOfNumber - 1) ? 0 : std::stoll(S.substr(pos + 1));
  37.  
  38. count += leftValue * right_multiplier * 3;
  39.  
  40. for (int d = 0; d < currentNumber; ++d) {
  41. if (isClap(d))
  42. count += right_multiplier;
  43. }
  44.  
  45. if (isClap(currentNumber))
  46. count += rightValue + 1;
  47.  
  48. right_multiplier *= 10;
  49. }
  50.  
  51. return count;
  52. }
  53. // Calculate claps from a to b
  54. long long solve(long long a, long long b) {
  55. return countClaps(b) - countClaps(a - 1);
  56. }
  57.  
  58. int main() {
  59. long long a, b;
  60. if (!checkInput(a, b)) {
  61. std::cout << "Invalid input! Please enter two integers a and b (1 <= a <= b <= 100000000) separated by a space." << std::endl;
  62. return 1;
  63. }
  64. std::cout << solve(a, b) << std::endl;
  65. return 0;
  66. }
Success #stdin #stdout 0.01s 5288KB
stdin
999999 10000000
stdout
19200006