Smallest number greater than or equal to N using only digits 1 to K | Java program to find the smallest number greater than or equal to N which is made up of first K digits ; Function to count the digits greater than K ; Function to print the list ; Function to find the number greater than or equal to n , which is only made of first k digits ; If the number itself satisfy the conditions ; Check digit from back ; If digit > K is present previously and current digit is less than K ; If current digit is greater than K ; If an extra digit needs to be added ; Print the number ; Driver Code
import java . util . * ; class GFG { static int CountGreater ( int n , int k ) { int a = 0 ; while ( n > 0 ) { if ( ( n % 10 ) > k ) { a ++ ; } n = n / 10 ; } return a ; } static void PrintList ( List < Integer > ans ) { for ( int it : ans ) System . out . print ( it ) ; } static void getNumber ( int n , int k ) { int count = CountGreater ( n , k ) ; if ( count == 0 ) { System . out . print ( n ) ; return ; } List < Integer > ans = new LinkedList < > ( ) ; boolean changed = false ; while ( n > 0 ) { int digit = n % 10 ; if ( changed == true ) { ans . add ( 0 , digit ) ; } else { if ( count == 0 && digit < k ) { ans . add ( 0 , digit + 1 ) ; changed = true ; } else { ans . add ( 0 , 1 ) ; if ( digit > k ) { count -- ; } } } n = n / 10 ; } if ( changed == false ) { ans . add ( 0 , 1 ) ; } PrintList ( ans ) ; return ; } public static void main ( String [ ] args ) { int N = 51234 ; int K = 4 ; getNumber ( N , K ) ; } }