fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // check if integer a has digit '7' in its decimal form
  5. bool has7(long long a) {
  6. while (a > 0) {
  7. if ((a % 10) == 7) return true;
  8. a /= 10;
  9. }
  10. return false;
  11. }
  12.  
  13. int solve_one(long long n) {
  14. // List of all-9 numbers up to 10 digits
  15. static long long all9[10] = {
  16. 9LL,
  17. 99LL,
  18. 999LL,
  19. 9999LL,
  20. 99999LL,
  21. 999999LL,
  22. 9999999LL,
  23. 99999999LL,
  24. 999999999LL,
  25. 9999999999LL
  26. };
  27.  
  28. int best = INT_MAX;
  29. for (int i = 0; i < 10; i++) {
  30. long long x = all9[i];
  31. long long cur = n;
  32. int steps = 0;
  33. // keep adding x until we see a '7'
  34. while (!has7(cur)) {
  35. cur += x;
  36. steps++;
  37. // (In practice, steps will be ≤ 10–12 here, because each digit
  38. // cycles mod 10.)
  39. }
  40. best = min(best, steps);
  41. }
  42. return best;
  43. }
  44.  
  45. int main() {
  46. ios::sync_with_stdio(false);
  47. cin.tie(nullptr);
  48.  
  49. int T;
  50. cin >> T;
  51. while (T--) {
  52. long long n;
  53. cin >> n;
  54. // If n already has a '7', 0 moves are needed
  55. if (has7(n)) {
  56. cout << 0 << "\n";
  57. } else {
  58. cout << solve_one(n) << "\n";
  59. }
  60. }
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0.01s 5280KB
stdin
16
51
60
61
777
12345689
1000000000
2002
3001
977
989898986
80
800001
96
70
15
90
stdout
3
2
1
0
1
3
5
4
0
7
1
2
7
0
7
3