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
< ? php function sumOfDigits ( $ n ) { $ res = 0 ; while ( $ n > 0 ) { $ res += $ n % 10 ; $ n /= 10 ; } return $ res ; } function findNumber ( $ n ) { $ i = $ n - 1 ; while ( $ i > 0 ) { if ( sumOfDigits ( $ i ) > sumOfDigits ( $ n ) ) return $ i ; $ i -- ; } return -1 ; } $ n = 824 ; echo findNumber ( $ n ) ; ? >