Maximum number made up of distinct digits whose sum is equal to N | Java program for the above approach ; Function to find the largest positive number made up of distinct digits having the sum of its digits as N ; If given number is greater than 45 , print - 1 ; Store the required number and the digit to be considered ; Loop until N > 0 and digit > 0 ; If the current digit is at most N then , add it to number num ; Update the value of num ; Decrement N by digit ; Consider the next lower digit ; Add 0 at the end and return the number num ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static long largestNumber ( int N ) { if ( N > 45 ) return - 1 ; int num = 0 , digit = 9 ; while ( N > 0 && digit > 0 ) { if ( digit <= N ) { num *= 10 ; num += digit ; N -= digit ; } digit -= 1 ; } return num * 10 ; } public static void main ( String [ ] args ) { int N = 25 ; System . out . print ( largestNumber ( N ) ) ; } }