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

24 Feb, 2022
Given a number n and we have to find n-th number such that it’s digits only consist 0, 1, 2, 3, 4 or 5.
Examples : 
Input: n = 6
Output: 5

Input:  n = 10
Output: 13
We first store 0, 1, 2, 3, 4, 5 in an array. We can see that next numbers will be 10, 11, 12,,13, 14, 15 and after that numbers will be 20, 21, 23, 24, 25 and so on. We can see the pattern that is repeating again and again. We save the calculated result and use it for further calculations. next 6 numbers are- 1*10+0 = 10 1*10+1 = 11 1*10+2 = 12 1*10+3 = 13 1*10+4 = 14 1*10+5 = 15and after that next 6 numbers will be- 2*10+0 = 20 2*10+1 = 21 2*10+2 = 22 2*10+3 = 23 2*10+4 = 24 2*10+5 = 25We use this pattern to find the n-th number. Below is complete algorithm.
1) push 0 to 5 in ans vector
2) for i=0 to n/6
     for j=0 to 6  
          // this will be the case when first 
          // digit will be zero 
          if (ans[i]*10! = 0) 
              ans.push_back(ans[i]*10 + ans[j])
3) print ans[n-1]
C++
Java
Python3
C#
Javascript
// C++ program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}#include <bits/stdc++.h>using namespace std; // Returns the N-th number with given digitsint findNth(int n){    // vector to store results    vector<int> ans;     // push first 6 numbers in the answer    for (int i = 0; i < 6; i++)        ans.push_back(i);     // calculate further results    for (int i = 0; i <= n / 6; i++)        for (int j = 0; j < 6; j++)            if ((ans[i] * 10) != 0)                ans.push_back(ans[i]                              * 10 + ans[j]);     return ans[n - 1];} // Driver codeint main(){    int n = 10;    cout << findNth(n);    return 0;}
// Java program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}import java.io.*;import java.util.*; class GFG{   // Returns the N-th number with given digits  public static int findNth(int n)  {    // vector to store results    ArrayList<Integer> ans = new ArrayList<Integer>();     // push first 6 numbers in the answer    for (int i = 0; i < 6; i++)      ans.add(i);     // calculate further results    for (int i = 0; i <= n / 6; i++)      for (int j = 0; j < 6; j++)        if ((ans.get(i) * 10) != 0)          ans.add(ans.get(i) * 10 + ans.get(j));    return ans.get(n - 1);  }   // Driver code  public static void main(String[] args)  {    int n = 10;    int ans = findNth(n);    System.out.println(ans);  }} // This code is contributed by RohitOberoi.
# Python3 program to find n-th number with digits# in {0, 1, 2, 3, 4, 5} # Returns the N-th number with given digitsdef findNth(n):     # vector to store results    ans = []     # push first 6 numbers in the answer    for i in range(6):        ans.append(i)     # calculate further results    for i in range(n // 6 + 1):        for j in range(6):            if ((ans[i] * 10) != 0):                ans.append(ans[i]                           * 10 + ans[j])     return ans[n - 1] # Driver codeif __name__ == "__main__":     n = 10    print(findNth(n))     # This code is contributed by ukasp.
// C# program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}using System;using System.Collections.Generic; class GFG{ // Returns the N-th number with given digitspublic static int findNth(int n){         // Vector to store results    List<int> ans = new List<int>();     // Push first 6 numbers in the answer    for(int i = 0; i < 6; i++)        ans.Add(i);     // Calculate further results    for(int i = 0; i <= n / 6; i++)        for(int j = 0; j < 6; j++)            if ((ans[i] * 10) != 0)                ans.Add(ans[i] * 10 + ans[j]);                     return ans[n - 1];} // Driver codepublic static void Main(String[] args){    int n = 10;    int ans = findNth(n);         Console.WriteLine(ans);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to find n-th// number with digits// in {0, 1, 2, 3, 4, 5}    // Returns the N-th number with given digits    function findNth(n)    {        // vector to store results        var ans = [];         // push first 6 numbers in the answer        for (i = 0; i < 6; i++)            ans.push(i);         // calculate further results        for (i = 0; i <= n / 6; i++)            for (j = 0; j < 6; j++)                if ((ans[i] * 10) != 0)                    ans.push(ans[i] * 10 + ans[j]);        return ans[n - 1];    }     // Driver code             var n = 10;        var ans = findNth(n);        document.write(ans); // This code contributed by Rajput-Ji </script>
13
Efficient Method :
Algorithm : 
First convert number n to base 6.Store the converted value simultaneously in an array.Print that array in reverse order.
First convert number n to base 6.
Store the converted value simultaneously in an array.
Print that array in reverse order.
Below is the implementation of the above algorithm:
C++
Java
Python3
C#
Javascript
// CPP code to find nth number// with digits 0, 1, 2, 3, 4, 5#include <bits/stdc++.h>using namespace std; #define max 100000 // function to convert num to base 6int baseconversion(int arr[], int num, int base) {    int i = 0, rem, j;     if (num == 0) {        return 0;    }     while (num > 0) {        rem = num % base;         arr[i++] = rem;         num /= base;    }     return i;} // Driver codeint main(){     // initialize an array to 0    int arr[max] = { 0 };     int n = 10;     // function calling to convert    // number n to base 6    int size = baseconversion(arr, n - 1, 6);     // if size is zero then return zero    if (size == 0)         cout << size;     for (int i = size - 1; i >= 0; i--) {         cout << arr[i];    }     return 0;} // Code is contributed by Anivesh Tiwari.
// Java code to find nth number// with digits 0, 1, 2, 3, 4, 5class GFG {         static final int max = 100000;         // function to convert num to base 6    static int baseconversion(int arr[],                          int num, int base)    {        int i = 0, rem, j;             if (num == 0) {            return 0;        }             while (num > 0) {                         rem = num % base;            arr[i++] = rem;            num /= base;        }             return i;    }         // Driver code    public static void main (String[] args)    {                 // initialize an array to 0        int arr[] = new int[max];             int n = 10;             // function calling to convert        // number n to base 6        int size = baseconversion(arr, n - 1, 6);             // if size is zero then return zero        if (size == 0)            System.out.print(size);             for (int i = size - 1; i >= 0; i--) {            System.out.print(arr[i]);        }    }} // This code is contributed by Anant Agarwal.
# Python code to find nth number# with digits 0, 1, 2, 3, 4, 5max = 100000; # function to convert num to base 6def baseconversion(arr, num, base):    i = 0;     if (num == 0):        return 0;    while (num > 0):         rem = num % base;        i = i + 1;        arr[i] = rem;        num = num//base;    return i;  # Driver codeif __name__ == '__main__':     # initialize an array to 0    arr = [0 for i in range(max)];    n = 10;     # function calling to convert    # number n to base 6    size = baseconversion(arr, n - 1, 6);     # if size is zero then return zero    if (size == 0):        print(size);     for i in range(size, 0, -1):        print(arr[i], end = ""); # This code is contributed by gauravrajput1
// C# code to find nth number// with digits 0, 1, 2, 3, 4, 5using System; class GFG {         static int max = 100000;         // function to convert num to base 6    static int baseconversion(int []arr,                              int num, int bas)    {        int i = 0, rem;             if (num == 0) {            return 0;        }             while (num > 0) {                         rem = num % bas;            arr[i++] = rem;            num /= bas;        }             return i;    }         // Driver code    public static void Main ()    {        // initialize an array to 0        int []arr = new int[max];             int n = 10;             // function calling to convert        // number n to base 6        int size = baseconversion(arr, n - 1, 6);             // if size is zero then return zero        if (size == 0)            Console.Write(size);             for (int i = size - 1; i >= 0; i--) {            Console.Write(arr[i]);        }    }} // This code is contributed by nitin mittal
<script>// javascript code to find nth number// with digits 0, 1, 2, 3, 4, 5var max = 100000;     // function to convert num to base 6    function baseconversion(arr , num , base) {        var i = 0, rem, j;         if (num == 0) {            return 0;        }         while (num > 0) {             rem = num % base;            arr[i++] = rem;            num = parseInt(num/base);        }         return i;    }     // Driver code              // initialize an array to 0        var arr = Array(max).fill(0);         var n = 10;         // function calling to convert        // number n to base 6        var size = baseconversion(arr, n - 1, 6);         // if size is zero then return zero        if (size == 0)            document.write(size);         for (i = size - 1; i >= 0; i--) {            document.write(arr[i]);        } // This code contributed by Rajput-Ji</script>
Output: 
13
Another Efficient Method:
Algorithm:
Decrease the number N by 1.2. Convert the number N to base 6.
Decrease the number N by 1.
2. Convert the number N to base 6.
Below is the implementation of the above algorithm :
C++
Java
Python3
C#
Javascript
// C++ code to find nth number// with digits 0, 1, 2, 3, 4, 5 #include <iostream>using namespace std; int ans(int n){  // If the Number is less than 6 return the number as it is.  if(n < 6){    return n;  }  //Call the function again and again the get the desired result.  //And convert the number to base 6.  return n%6 + 10*(ans(n/6));} int getSpecialNumber(int N){  //Decrease the Number by 1 and Call ans function  // to convert N to base 6  return ans(--N);} /*Example:-Input: N = 17Output: 24 Explanation:-decrease 17 by 1N = 16call ans() on 16 ans():    16%6 + 10*(ans(16/6))        since 16/6 = 2 it is less than 6 the ans returns value as it is.    4 + 10*(2)    = 24 hence answer is 24.*/ int main(){  int N = 17;  int answer = getSpecialNumber(N);  cout<<answer<<endl;  return 0;} // This Code is contributed by Regis Caelum
// Java code to find nth number// with digits 0, 1, 2, 3, 4, 5import java.util.*; class GFG{ static int ans(int n){         // If the Number is less than 6 return    // the number as it is.    if (n < 6)    {        return n;    }         // Call the function again and again    // the get the desired result.    // And convert the number to base 6.    return n % 6 + 10 * (ans(n / 6));} static int getSpecialNumber(int N){         // Decrease the Number by 1 and Call    // ans function to convert N to base 6    return ans(--N);} /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less * than 6 the ans returns value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */// Driver codepublic static void main(String[] args){    int N = 17;    int answer = getSpecialNumber(N);         System.out.println(answer);}} // This code is contributed by Rajput-Ji
# Python3 code to find nth number# with digits 0, 1, 2, 3, 4, 5def ans(n):     # If the Number is less than 6 return    # the number as it is.    if (n < 6):        return n         # Call the function again and again    # the get the desired result.    # And convert the number to base 6.    return n % 6 + 10 * (ans(n // 6)) - 1 def getSpecialNumber(N):         # Decrease the Number by 1 and Call    # ans function to convert N to base 6    return ans(N) ''' * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns * value as it is. 4 + 10*(2) = 24 * * hence answer is 24. '''# Driver codeif __name__ == '__main__':         N = 17    answer = getSpecialNumber(N)     print(answer) # This code contributed by aashish1995
// C# code to find nth number// with digits 0, 1, 2, 3, 4, 5using System; public class GFG{ static int ans(int n){         // If the Number is less than 6 return    // the number as it is.    if (n < 6)    {        return n;    }         // Call the function again and again    // the get the desired result.    // And convert the number to base 6.    return n % 6 + 10 * (ans(n / 6));} static int getSpecialNumber(int N){         // Decrease the Number by 1 and Call    // ans function to convert N to base 6    return ans(--N);} /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less * than 6 the ans returns value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */// Driver codepublic static void Main(String[] args){    int N = 17;    int answer = getSpecialNumber(N);         Console.WriteLine(answer);}}  // This code is contributed by Rajput-Ji
<script>// javascript code to find nth number// with digits 0, 1, 2, 3, 4, 5     function ans(n) {         // If the Number is less than 6 return        // the number as it is.        if (n < 6) {            return n;        }         // Call the function again and again        // the get the desired result.        // And convert the number to base 6.        return n % 6 + 10 * (ans(parseInt(n / 6)));    }     function getSpecialNumber(N) {         // Decrease the Number by 1 and Call        // ans function to convert N to base 6        return ans(--N);    }     /*     * Example:- Input: N = 17 Output: 24     *     * Explanation:- decrease 17 by 1 N = 16 call ans() on 16     *     * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns     * value as it is. 4 + 10*(2) = 24     *     * hence answer is 24.     */    // Driver code             var N = 17;        var answer = getSpecialNumber(N);         document.write(answer); // This code contributed by Rajput-Ji</script>
24
Time Complexity: O(logN)Auxiliary Space: O(1)
nitin mittal
regiscaelum
mulchandanimanisha5
RohitOberoi
ukasp
Rajput-Ji
aashish1995
GauravRajput1
kk9826225
Morgan Stanley
number-digits
Dynamic Programming
Mathematical
Morgan Stanley
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7