Smallest number greater than or equal to N using only digits 1 to K | 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
def CountGreater ( n , k ) : NEW_LINE INDENT a = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( ( n % 10 ) > k ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT return a NEW_LINE DEDENT def PrintList ( ans ) : NEW_LINE INDENT for i in ans : NEW_LINE INDENT print ( i , end = ' ' ) NEW_LINE DEDENT DEDENT def getNumber ( n , k ) : NEW_LINE INDENT count = CountGreater ( n , k ) NEW_LINE if ( count == 0 ) : NEW_LINE INDENT print ( n ) NEW_LINE return NEW_LINE DEDENT ans = [ ] NEW_LINE changed = False NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 NEW_LINE if ( changed == True ) : NEW_LINE INDENT ans . insert ( 0 , digit ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( count == 0 and digit < k ) : NEW_LINE INDENT ans . insert ( 0 , digit + 1 ) NEW_LINE changed = True NEW_LINE DEDENT else : NEW_LINE INDENT ans . insert ( 0 , 1 ) NEW_LINE if ( digit > k ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT DEDENT DEDENT n = n // 10 NEW_LINE DEDENT if ( changed == False ) : NEW_LINE INDENT ans . insert ( 0 , 1 ) NEW_LINE DEDENT PrintList ( ans ) NEW_LINE return NEW_LINE DEDENT N = 51234 NEW_LINE K = 4 NEW_LINE getNumber ( N , K ) NEW_LINE