Find first n numbers with given set of digits Java

PROGRAM TO FIND NTH NUMBER WITH DIGITS IN {0, 1, 2, 3, 4, 5}



import java.util.*;
 
class MAIN{
 
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
 *
 * Explaination:- 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
public static void main(String[] args)
{
    int N = 17;
    int answer = getSpecialNumber(N);
     
    System.out.println(answer);
}
}


OUTPUT:
24

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java