Largest number less than N with digit sum greater than the digit sum of N | Function to return the sum of the digits of n ; Loop for each digit of the number ; Function to return the greatest number less than n such that the sum of its digits is greater than the sum of the digits of n ; Starting from n - 1 ; Check until 1 ; If i satisfies the given condition ; If the condition is not satisfied ; Driver code
def sumOfDigits ( n ) : NEW_LINE INDENT res = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT res += n % 10 NEW_LINE n /= 10 NEW_LINE DEDENT return res ; NEW_LINE DEDENT def findNumber ( n ) : NEW_LINE INDENT i = n - 1 ; NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( sumOfDigits ( i ) > sumOfDigits ( n ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 824 ; NEW_LINE print ( findNumber ( n ) ) NEW_LINE DEDENT