Smallest number greater than Y with sum of digits equal to X | Java program for the above approach ; Function to return the minimum String of length d having the sum of digits s ; Return a String of length d ; Greedily put 9 's in the end ; Put remaining sum ; Function to find the smallest number greater than Y whose sum of digits is X ; Convert number y to String ; Maintain prefix sum of digits ; Iterate over Y from the back where k is current length of suffix ; Stores current digit ; Increase current digit ; Sum upto current prefix ; Return answer if remaining sum can be obtained in suffix ; Find suffix of length k having sum of digits x - r ; Append current character ; Return the result ; Driver code ; Given number and sum ; Function call
import java . util . * ; @ SuppressWarnings ( " unchecked " ) class GFG { static String helper ( int d , int s ) { StringBuilder ans = new StringBuilder ( ) ; for ( int i = 0 ; i < d ; i ++ ) { ans . append ( "0" ) ; } for ( int i = d - 1 ; i >= 0 ; i -- ) { if ( s >= 9 ) { ans . setCharAt ( i , '9' ) ; s -= 9 ; } else { char c = ( char ) ( s + ( int ) '0' ) ; ans . setCharAt ( i , c ) ; s = 0 ; } } return ans . toString ( ) ; } static String findMin ( int x , int Y ) { String y = Integer . toString ( Y ) ; int n = y . length ( ) ; ArrayList p = new ArrayList ( ) ; for ( int i = 0 ; i < n ; i ++ ) { p . add ( 0 ) ; } for ( int i = 0 ; i < n ; i ++ ) { p . add ( i , ( int ) ( ( int ) y . charAt ( i ) - ( int ) '0' ) ) ; if ( i > 0 ) { p . add ( i , ( int ) p . get ( i ) + ( int ) p . get ( i - 1 ) ) ; } } for ( int i = n - 1 , k = 0 ; ; i -- , k ++ ) { int d = 0 ; if ( i >= 0 ) { d = ( int ) y . charAt ( i ) - ( int ) '0' ; } for ( int j = d + 1 ; j <= 9 ; j ++ ) { int r = j ; if ( i > 0 ) { r += ( int ) p . get ( i - 1 ) ; } if ( x - r >= 0 && x - r <= 9 * k ) { String suf = helper ( k , x - r ) ; String pre = " " ; if ( i > 0 ) pre = y . substring ( 0 , i ) ; char cur = ( char ) ( j + ( int ) '0' ) ; pre += cur ; return pre + suf ; } } } } public static void main ( String [ ] arg ) { int x = 18 ; int y = 99 ; System . out . print ( findMin ( x , y ) ) ; } }