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.

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.

Input & Output

Example 1 — Basic Case
$ Input: n = 16, target = 6
Output: 4
💡 Note: n=16 has digit sum 1+6=7 > 6. Adding 4 gives us 20 with digit sum 2+0=2 ≤ 6.
Example 2 — Already Beautiful
$ Input: n = 467, target = 20
Output: 0
💡 Note: n=467 has digit sum 4+6+7=17 ≤ 20, so it's already beautiful.
Example 3 — Large Rounding
$ Input: n = 1, target = 1
Output: 0
💡 Note: n=1 has digit sum 1 ≤ 1, so it's already beautiful.

Constraints

  • 1 ≤ n ≤ 1012
  • 1 ≤ target ≤ 150

Visualization

Tap to expand
Make Integer Beautiful: Transform n to minimize digit sumInputn = 16target = 6Current: 1+6 = 7 > 6Need to reduce digit sumTry: 16 + 4 = 20Resultx = 420: 2+0=2≤6Strategy: Round up to next power of 10 to minimize digit sum
Understanding the Visualization
1
Input
Number n=16, target=6
2
Process
Current sum=7>6, need to reduce
3
Output
Add 4 to get 20 with sum=2≤6
Key Takeaway
🎯 Key Insight: Rounding up digits to powers of 10 can drastically reduce digit sum with minimal addition
Asked in
Google 12 Microsoft 8 Amazon 5
23.4K Views
Medium Frequency
~15 min Avg. Time
847 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