Minimum count of digits required to obtain given Sum
Given an integer N, the task is to find the minimum number of digits required to generate a number having the sum of digits equal to N.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: N = 18
The number with smallest number of digits having sum of digits equal to 18 is 99.
Input: N = 28
4-digit numbers like 8884, 6877, etc are the smallest in length having sum of digits equal to 28.
Approach: The problem can be solved by the following observations:
- Increment count by 9. Therefore, now count is equal to the number of 9’s in the shortest number. Reduce N to N % 9
- Now, if N exceeds 0, increment count by 1.
- Finally, print count as the answer.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)