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
function sumOfDigits ( n ) { var res = 0 ; while ( n > 0 ) { res += n % 10 ; n = parseInt ( n / 10 ) ; } return res ; } function findNumber ( n ) { var i = n - 1 ; while ( i > 0 ) { if ( sumOfDigits ( i ) > sumOfDigits ( n ) ) return i ; i -- ; } return - 1 ; } var n = 824 ; document . write ( findNumber ( n ) ) ;