Minimum Addition to Make Integer Beautiful - Problem

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.

Your task is to find the minimum non-negative integer x such that n + x is beautiful.

Example: If n = 16 and target = 6, then n has digit sum 1 + 6 = 7 > 6, so it's not beautiful. We need to add x = 4 to get 16 + 4 = 20, which has digit sum 2 + 0 = 2 โ‰ค 6.

The input guarantees that it's always possible to make n beautiful by adding some non-negative value.

Input & Output

example_1.py โ€” Python
$ Input: n = 16, target = 6
โ€บ Output: 4
๐Ÿ’ก Note: The digit sum of 16 is 1 + 6 = 7, which is greater than target = 6. By adding 4, we get 16 + 4 = 20, and the digit sum of 20 is 2 + 0 = 2, which is less than or equal to 6.
example_2.py โ€” Python
$ Input: n = 467, target = 6
โ€บ Output: 33
๐Ÿ’ก Note: The digit sum of 467 is 4 + 6 + 7 = 17 > 6. We need to add 33 to get 467 + 33 = 500. The digit sum of 500 is 5 + 0 + 0 = 5 โ‰ค 6.
example_3.py โ€” Python
$ Input: n = 1, target = 1
โ€บ Output: 0
๐Ÿ’ก Note: The digit sum of 1 is 1, which equals the target. So we don't need to add anything, the answer is 0.

Constraints

  • 1 โ‰ค n โ‰ค 1012
  • 1 โ‰ค target โ‰ค 150
  • The input will be generated such that it is always possible to make n beautiful

Visualization

Tap to expand
Digit Transformation StrategyExample: n=467, target=64674 + 6 + 7 = 17Target: 6Round Up+335005 + 0 + 0 = 5โœ“ โ‰ค 6Key Strategy Steps:1Check current digit sum: 4 + 6 + 7 = 17 > 62Identify rounding opportunity: Round 467 โ†’ 5003Create trailing zeros: 500 has digit sum 5 + 0 + 0 = 54Calculate difference: 500 - 467 = 33๐ŸŽฏ Result: Add 33 to make the number beautiful!
Understanding the Visualization
1
Identify the problem
Check if current digit sum exceeds target
2
Find the rounding point
Determine which digit position to round up
3
Execute the transformation
Round up and set trailing digits to zero
4
Verify and return
Calculate the difference as our answer
Key Takeaway
๐ŸŽฏ Key Insight: Instead of incrementing one by one, we can strategically round up to powers of 10 to create zeros and minimize digit sum efficiently.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen