#2457
Minimum Addition to Make Integer Beautiful
MediumMathGreedyGreedyMathematical Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log n)Space O(1)
Instead of checking each x, we can directly calculate how much we need to add to make the digit sum beautiful by rounding up the digits of n to the next multiple of 10.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the digit sum of n.
- 2Step 2: If the digit sum is already less than or equal to target, return 0.
- 3Step 3: Starting from the least significant digit, find the first digit that causes the digit sum to exceed target.
- 4Step 4: Calculate how much to add to turn this digit into zero and carry over to the next digit.
- 5Step 5: Return the calculated addition.
solution.py18 lines
1# Full working Python code
2
3def min_addition(n, target):
4 def digit_sum(num):
5 return sum(int(d) for d in str(num))
6 if digit_sum(n) <= target:
7 return 0
8 x = 0
9 multiplier = 1
10 while digit_sum(n) > target:
11 last_digit = n % 10
12 if last_digit != 0:
13 x += (10 - last_digit) * multiplier
14 n += (10 - last_digit) * multiplier
15 n //= 10
16 multiplier *= 10
17 return x
18ℹ
Complexity note: The time complexity is O(log n) because we are processing each digit of n, which has at most log n digits.
- 1Understanding digit sums is crucial for this problem.
- 2Rounding up digits can help quickly achieve the target.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.