Minimum value of X that can be added to N to minimize sum of the digits to Ã ¢ â €°¤ K | Java program for the above approach ; Function to find the minimum number needed to be added so that the sum of the digits does not exceed K ; Find the number of digits ; Calculate sum of the digits ; Add the digits of num2 ; If the sum of the digits of N is less than or equal to K ; No number needs to be added ; Otherwise ; Calculate the sum of digits from least significant digit ; If sum exceeds K ; Increase previous digit by 1 ; Add zeros to the end ; Calculate difference between the result and N ; Return the result ; Driver Code
import java . util . * ; import java . io . * ; class GFG { static int minDigits ( int N , int K ) { int digits_num = ( int ) Math . floor ( Math . log ( N ) + 1 ) ; int temp_sum = 0 ; int temp = digits_num ; int result = 0 ; int X , var ; int sum = 0 ; int num2 = N ; while ( num2 != 0 ) { sum += num2 % 10 ; num2 /= 10 ; } if ( sum <= K ) { X = 0 ; } else { while ( temp > 0 ) { var = ( N / ( ( int ) Math . pow ( 10 , temp - 1 ) ) ) ; temp_sum += var % 10 ; if ( temp_sum >= K ) { var /= 10 ; var ++ ; result = var * ( int ) Math . pow ( 10 , temp ) ; break ; } temp -- ; } X = result - N ; return X ; } return - 1 ; } public static void main ( String args [ ] ) { int N = 11 ; int K = 1 ; System . out . println ( minDigits ( N , K ) ) ; } }