text: Smallest number greater than Y with sum of digits equal to X | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; string helper ( int d , int s ) { string ans ( d , '0' ) ; for ( int i = d - 1 ; i >= 0 ; i -- ) { if ( s >= 9 ) { ans [ i ] = '9' ; s -= 9 ; } else { char c = ( char ) s + '0' ; ans [ i ] = c ; s = 0 ; } } return ans ; } string findMin ( int x , int Y ) { string y = to_string ( Y ) ; int n = y . size ( ) ; vector < int > p ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { p [ i ] = y [ i ] - '0' ; if ( i > 0 ) p [ i ] += p [ i - 1 ] ; } for ( int i = n - 1 , k = 0 ; ; i -- , k ++ ) { int d = 0 ; if ( i >= 0 ) d = y [ i ] - '0' ; for ( int j = d + 1 ; j <= 9 ; j ++ ) { int r = ( i > 0 ) * p [ i - 1 ] + j ; if ( x - r >= 0 and x - r <= 9 * k ) { string suf = helper ( k , x - r ) ; string pre = " " ; if ( i > 0 ) pre = y . substr ( 0 , i ) ; char cur = ( char ) j + '0' ; pre += cur ; return pre + suf ; } } } } int main ( ) { int x = 18 ; int y = 99 ; cout << findMin ( x , y ) << endl ; return 0 ; }