Find the Number which contain the digit d in C++

C++Server Side ProgrammingProgramming

Consider we have a digit d, and the upper limit n. we have to find all numbers that contains d in range 0 to n. So if n = 20, and digit is 3, then the numbers will be [3, 13].

To solve this problem, we will take every number as string, then if the digit is present in the string, the number will be printed, otherwise ignored.

Example

#include<iostream>
using namespace std;
int getAllNumWithDigit(int n, int d) {
   string str = "";
   str += to_string(d);
   char ch = str[0];
   string p = "";
   p += ch;
   for (int i = 0; i <= n; i++) {
      str = "";
      str = str + to_string(i);
      int index = str.find(p);
      if (i == d || index!=-1)
         cout << (i) << " ";
   }
}
int main() {
   int n = 100; int d = 3;
   getAllNumWithDigit(n, d);
}

Output

3 13 23 30 31 32 33 34 35 36 37 38 39 43 53 63 73 83 93
raja
Published on 04-Nov-2019 08:01:20
Advertisements