Minimize the number by changing at most K digits | Function to return the minimized number ; Total digits in the number ; If the string is empty or there are no operations to perform ; "0" is a valid number ; If the first digit is not already 1 then update it to 1 and decrement k ; While there are operations left and the number can still be updated ; If the current digit is not already 0 then update it to 0 and decrement k ; Return the minimised number ; Driver code
def minNum ( num , k ) : NEW_LINE INDENT len_ = len ( num ) NEW_LINE if len_ == 0 or k == 0 : NEW_LINE INDENT return num NEW_LINE DEDENT if len_ == 1 : NEW_LINE INDENT return "0" NEW_LINE DEDENT if num [ 0 ] != '1' : NEW_LINE INDENT num = '1' + num [ 1 : ] NEW_LINE k -= 1 NEW_LINE DEDENT i = 1 NEW_LINE while k > 0 and i < len_ : NEW_LINE INDENT if num [ i ] != '0' : NEW_LINE INDENT num = num [ : i ] + '0' + num [ i + 1 : ] NEW_LINE k -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return num NEW_LINE DEDENT num = "91945" NEW_LINE k = 3 NEW_LINE print ( minNum ( num , k ) ) NEW_LINE