Smallest number greater than or equal to N having sum of digits not exceeding S | Java program for the above approach ; Function to calculate sum digits of n ; Function to find the smallest possible integer satisfying the given condition ; If the sum of digits is already smaller than S ; Initialize variables ; Finding last kth digit ; Add remaining to make digit 0 ; If sum of digits does not exceed S ; Update k ; Driver Code ; Given N and S ; Function call
import java . io . * ; class GFG { static int sum ( int n ) { int res = 0 ; while ( n > 0 ) { res += n % 10 ; n /= 10 ; } return res ; } static int smallestNumber ( int n , int s ) { if ( sum ( n ) <= s ) { return n ; } int ans = n , k = 1 ; for ( int i = 0 ; i < 9 ; ++ i ) { int digit = ( ans / k ) % 10 ; int add = k * ( ( 10 - digit ) % 10 ) ; ans += add ; if ( sum ( ans ) <= s ) { break ; } k *= 10 ; } return ans ; } public static void main ( String [ ] args ) { int N = 3 , S = 2 ; System . out . println ( smallestNumber ( N , S ) ) ; } }