Biggest integer which has maximum digit sum in range from 1 to n | function to calculate the sum of digits of a number . ; Returns the maximum number with maximum sum of digits . ; initializing b as 1 and initial max sum to be of n ; iterates from right to left in a digit ; while iterating this is the number from right to left ; calls the function to check if sum of cur is more then of ans ; reduces the number to one unit less ; driver program to test the above function
def sumOfDigits ( a ) : NEW_LINE INDENT sm = 0 NEW_LINE while ( a != 0 ) : NEW_LINE INDENT sm = sm + a % 10 NEW_LINE a = a // 10 NEW_LINE DEDENT return sm NEW_LINE DEDENT def findMax ( x ) : NEW_LINE INDENT b = 1 NEW_LINE ans = x NEW_LINE while ( x != 0 ) : NEW_LINE INDENT cur = ( x - 1 ) * b + ( b - 1 ) NEW_LINE if ( sumOfDigits ( cur ) > sumOfDigits ( ans ) or ( sumOfDigits ( cur ) == sumOfDigits ( ans ) and cur > ans ) ) : NEW_LINE INDENT ans = cur NEW_LINE DEDENT x = x // 10 NEW_LINE b = b * 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 521 NEW_LINE print ( findMax ( n ) ) NEW_LINE