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
Published on 26-Jun-2021 14:21:08
- Related Questions & Answers
- Program to find sum of series 1*2*3 + 2*3*4+ 3*4*5 + . . . + n*(n+1)*(n+2) in C++
- Sum of the Series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... in C++\n
- Find (1^n + 2^n + 3^n + 4^n) mod 5 in C++
- C++ program to find the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + … + (n*n)
- C++ Programe to find n-th term in series 1 2 2 3 3 3 4
- Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n) in C++
- Program to find N-th term of series 0, 2,1, 3, 1, 5, 2, 7, 3...in C++
- Program to find N-th term of series 0, 0, 2, 1, 4, 2, 6, 3, 8…in C++
- Finding n-th number made of prime digits (2, 3, 5 and 7) only in C++
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 in C++
- Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. in C++
- Find value of (n^1 + n^2 + n^3 + n^4) mod 5 for given n in C++
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n – 1)^2
- C++ Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! + …… n/n!
- C++ program to find the sum of the series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!