Largest number less than N with digit sum greater than the digit sum of N | Java implementation of the approach ; 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
import java . io . * ; class GFG { static int sumOfDigits ( int n ) { int res = 0 ; while ( n > 0 ) { res += n % 10 ; n /= 10 ; } return res ; } static int findNumber ( int n ) { int i = n - 1 ; while ( i > 0 ) { if ( sumOfDigits ( i ) > sumOfDigits ( n ) ) return i ; i -- ; } return - 1 ; } public static void main ( String [ ] args ) { int n = 824 ; System . out . println ( findNumber ( n ) ) ; } }