Minimum value of X that can be added to N to minimize sum of the digits to Ã ¢ â €°¤ K | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDigits ( int N , int K ) { int digits_num = floor ( log10 ( N ) + 1 ) ; int temp_sum = 0 ; int temp = digits_num ; int result ; 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 / ( pow ( 10 , temp - 1 ) ) ) ; temp_sum += var % 10 ; if ( temp_sum >= K ) { var /= 10 ; var ++ ; result = var * pow ( 10 , temp ) ; break ; } temp -- ; } X = result - N ; return X ; } } int main ( ) { int N = 11 , K = 1 ; cout << minDigits ( N , K ) ; return 0 ; }