n-th number with digits in {0, 1, 2, 3, 4, 5} in C++


The numbers formed with the digits {0, 1, 2, 3, 4, 5} are

0, 1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, etc..,

We can form the above sequence using the first 6 digits. Let's see an example of the formation of numbers.

1 * 10 + 0 = 10
1 * 10 + 1 = 11
1 * 10 + 2 = 12
1 * 10 + 3 = 13
1 * 10 + 4 = 14
1 * 10 + 5 = 15

Similarly, apply for the number 2, 3, 4, 5. You will get the next 6 numbers with 2 using the above pattern. And then 3 after that 4 and 5.

Algorithm

  • Initialise the number n.
  • Initialise a vector.
  • Write a loop that iterates from 0 to 5.
    • Push all the numbers to vector.
  • We have first six numbers of the series.
  • Write a loop that iterates from 0 to n / 6.
    • Write a loop that iterates from 0 to 5.
      • Generate remaining numbers with the above discussed pattern.
      • Push them to the vector.
  • Return the n-th number from the sequence.

Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>

using namespace std;

int findNthNumber(int n) {
   vector<int> numbers;

   for (int i = 0; i < 6; i++) {
      numbers.push_back(i);
   }
   for (int i = 0; i <= n / 6; i++) {
      for (int j = 0; j < 6; j++) {
         if ((numbers[i] * 10) != 0) {
            numbers.push_back(numbers[i] * 10 + numbers[j]);
         }
      }
   }
   return numbers[n - 1];
}
int main() {
   int n = 7;
   cout << findNthNumber(n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

10

Updated on: 22-Oct-2021

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements