Largest number less than N with digit sum greater than the digit sum of N | C ++ 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
#include <iostream> NEW_LINE using namespace std ; int sumOfDigits ( int n ) { int res = 0 ; while ( n > 0 ) { res += n % 10 ; n /= 10 ; } return res ; } int findNumber ( int n ) { int i = n - 1 ; while ( i > 0 ) { if ( sumOfDigits ( i ) > sumOfDigits ( n ) ) return i ; i -- ; } return -1 ; } int main ( ) { int n = 824 ; cout << findNumber ( n ) ; return 0 ; }