text: Biggest integer which has maximum digit sum in range from 1 to n | Java program to find the number with maximum digit sum . ; 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 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
code: import java . io . * ; class GFG { static int sumOfDigits ( int a ) { int sum = 0 ; while ( a != 0 ) { sum += a % 10 ; a /= 10 ; } return sum ; } static int findMax ( int x ) { int b = 1 , ans = x ; while ( x != 0 ) { int cur = ( x - 1 ) * b + ( b - 1 ) ; if ( sumOfDigits ( cur ) > sumOfDigits ( ans ) || ( sumOfDigits ( cur ) == sumOfDigits ( ans ) && cur > ans ) ) ans = cur ; x /= 10 ; b *= 10 ; } return ans ; } public static void main ( String [ ] args ) { int n = 521 ; System . out . println ( findMax ( n ) ) ; } }