Problem · Greedy
Smallest Number With a Given Digit Sum
Learn this problemProblem statement
Given integers digitSum and numberOfDigits, construct the smallest non-negative decimal number that:
- has exactly
numberOfDigitsdigits, and - has digits whose sum is exactly
digitSum.
Return the number as a string. The first digit cannot be zero unless numberOfDigits is 1. The input is guaranteed to admit at least one valid number.
Function
smallestNumberWithDigitSum(digitSum: int, numberOfDigits: int) → StringExamples
Example 1
digitSum = 20numberOfDigits = 3return = "299"The smallest three-digit number with digit sum 20 is 299. Any smaller hundreds digit would leave more than 18 for the final two digits.
Example 2
digitSum = 1numberOfDigits = 4return = "1000"The leading digit must be nonzero, so 1000 is the smallest four-digit number with digit sum 1.
Constraints
1 <= numberOfDigits.0 <= digitSum <= 9 * numberOfDigits.- If
numberOfDigitsis greater than1, thendigitSumis positive. - The returned string has exactly
numberOfDigitscharacters and no leading zero.