text: 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
code: < ? php function sumOfDigits ( $ a ) { $ sum = 0 ; while ( $ a ) { $ sum += $ a % 10 ; $ a = ( int ) $ a / 10 ; } return $ sum ; } function findMax ( $ x ) { $ b = 1 ; $ ans = $ x ; while ( $ x ) { $ cur = ( $ x - 1 ) * $ b + ( $ b - 1 ) ; if ( sumOfDigits ( $ cur ) > sumOfDigits ( $ ans ) || ( sumOfDigits ( $ cur ) == sumOfDigits ( $ ans ) && $ cur > $ ans ) ) $ ans = $ cur ; $ x = ( int ) $ x / 10 ; $ b *= 10 ; } return $ ans ; } $ n = 521 ; echo findMax ( $ n ) ; ? >