Minimum Addition to Make Integer Beautiful Problem
Description
LeetCode Problem 2457.
You are given two positive integers n and target.
An integer is considered beautiful if the sum of its digits is less than or equal to target.
Return the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.
Example 1:
Input: n = 16, target = 6
Output: 4
Explanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.
Example 2:
Input: n = 467, target = 6
Output: 33
Explanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.
Example 3:
Input: n = 1, target = 1
Output: 0
Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.
Constraints:
1 <= n <= 10^121 <= target <= 150- The input will be generated such that it is always possible to make
nbeautiful.
Solution
Approach: Greedy
Let f(x) be the digit sum of x. We want the smallest x >= 0 with f(n + x) <= target.
While the digit sum of y = n + x is too big, take the lowest non-zero digit of y, turn it into 0 and add 1 to the digit just above it (this is the cheapest way to shrink the digit sum). Record the new x and repeat.
For example, with n = 467 and target = 6 the value goes 467 -> 470 -> 500, so the answer is 33.
Complexity: O(log2 n) time and O(1) space.
class Solution:
def makeIntegerBeautiful(self, n: int, target: int) -> int:
def f(x: int) -> int:
y = 0
while x:
y += x % 10
x //= 10
return y
x = 0
while f(n + x) > target:
y = n + x
p = 10
while y % 10 == 0:
y //= 10
p *= 10
x = (y // 10 + 1) * p - n
return x