Advertisement
st3p

How many numbers have k

Jul 9th, 2017
975
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. // У скольких целых чисел, лежащих в диапазоне от 1 до n, есть цифра k?
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6.     int n, k, counter = 0;
  7.     cout << "Enter number from 1 to 9999: ";
  8.     cin >> n;
  9.     cout << "Enter searching number (from 1 to 9): ";
  10.     cin >> k;
  11.     if (n > 9999 || n < 1) {
  12.         cout << "Entered number is invalid\n";
  13.         system("pause");
  14.         main();
  15.     }
  16.     if (k<=0||k>9) {
  17.         cout << "Entered searching number is invalid\n";
  18.         system("pause");
  19.         main();
  20.     }
  21.     for (int i = 1; i <= n; i++) {
  22.         if (i == k) {
  23.             counter++;
  24.             continue;
  25.         }
  26.         if (i > 10 && i < 100) {
  27.             if (i / 10 == k) {
  28.                 counter++;
  29.                 continue;
  30.             }
  31.             if (i % 10 == k) {
  32.                 counter++;
  33.                 continue;
  34.             }
  35.         }
  36.         if (i > 100 && i<1000) {
  37.             if (i / 100 == k) {
  38.                 counter++;
  39.                 continue;
  40.             }
  41.             if ((i % 100) / 10 == k) {
  42.                 counter++;
  43.                 continue;
  44.             }
  45.             if ((i % 100) % 10 == k) {
  46.                 counter++;
  47.                 continue;
  48.             }
  49.         }
  50.         if (i > 1000) {
  51.             if (i / 1000 == k) {
  52.                 counter++;
  53.                 continue;
  54.             }
  55.             if ((i % 1000) / 100 == k) {
  56.                 counter++;
  57.                 continue;
  58.             }
  59.             if (((i % 1000) % 100) / 10 == k) {
  60.                 counter++;
  61.                 continue;
  62.             }
  63.             if (((i % 1000) % 100) % 10 == k) {
  64.                 counter++;
  65.                 continue;
  66.             }
  67.         }
  68.     }
  69.     cout << "There are " << counter << " numbers between 1 and " << n << " that have " << k << endl;
  70.     system("pause");
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement