Problem Description
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.
Key Insights
- The problem requires checking the digit sum of a number and adjusting it to meet a target value.
- To make
n
beautiful, we can incrementn
by a non-negative integerx
until the digit sum is less than or equal totarget
. - The digit sum can be easily calculated by converting the number to a string and summing the integer values of its characters.
- The approach involves incrementally finding the next number after
n
that has a digit sum ≤ target.
Space and Time Complexity
Time Complexity: O(d), where d is the number of digits in n
(up to 12).
Space Complexity: O(1), as we are using a constant amount of space.
Solution
To solve the problem, we will use a greedy approach. We will repeatedly check the digit sum of n + x
for increasing values of x
until the sum is less than or equal to target
. The algorithm can be summarized as follows:
- Initialize
x
to 0. - While the digit sum of
n + x
is greater thantarget
, incrementx
and check again. - Return the value of
x
when the condition is met.
We will utilize an iterative approach to compute the digit sum each time we increment x
.