Minimum value of X that can be added to N to minimize sum of the digits to Ã ¢ â €°¤ K | 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
function minDigits ( N , K ) { let digits_num = Math . floor ( Math . log ( N ) / Math . log ( 10 ) + 1 ) ; let temp_sum = 0 ; let temp = digits_num ; let result ; let X , var1 ; let sum = 0 ; let num2 = N ; while ( num2 != 0 ) { sum += num2 % 10 ; num2 = parseInt ( num2 / 10 ) ; } if ( sum <= K ) { X = 0 ; } else { while ( temp > 0 ) { var1 = parseInt ( N / ( Math . pow ( 10 , temp - 1 ) ) ) ; temp_sum += var1 % 10 ; if ( temp_sum >= K ) { var1 = parseInt ( var1 / 10 ) ; var1 ++ ; result = var1 * Math . pow ( 10 , temp ) ; break ; } temp -- ; } X = result - N ; return X ; } } let N = 11 , K = 1 ; document . write ( minDigits ( N , K ) ) ;