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 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 Code
function sumOfDigits ( a ) { var sum = 0 ; while ( a != 0 ) { sum += a % 10 ; a = parseInt ( a / 10 ) ; } return sum ; } function findMax ( x ) { var b = 1 , ans = x ; while ( x != 0 ) { var cur = ( x - 1 ) * b + ( b - 1 ) ; if ( sumOfDigits ( cur ) > sumOfDigits ( ans ) || ( sumOfDigits ( cur ) == sumOfDigits ( ans ) && cur > ans ) ) ans = cur ; x = parseInt ( x / 10 ) ; b *= 10 ; } return ans ; } var n = 521 ; document . write ( findMax ( n ) ) ;