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
Minimum Addition to Make Integer Beautiful INPUT Number n = 16 1 6 Digit Sum: 1 + 6 = 7 Target 6 Current sum: 7 Target: 6 7 > 6 (Not Beautiful!) n = 16, target = 6 Find minimum x to add ALGORITHM STEPS 1 Check digit sum Sum(16) = 1+6 = 7 > 6 2 Round last digit up 16 + 4 = 20 (next 10) 20 --> 16 --> 20 +4 3 Check new sum Sum(20) = 2+0 = 2 4 Verify result 2 <= 6 (OK!) Greedy Strategy: Round up rightmost digit to reduce digit sum. Repeat until sum <= target FINAL RESULT Before: n = 16 1 6 Sum = 7 (too high) After: n + x = 20 2 0 Sum = 2 <= 6 (OK!) Output x = 4 16 + 4 = 20 is beautiful Key Insight: Greedy rounding: To reduce digit sum, round up the current position to the next power of 10. This zeros out lower digits and increments higher ones. Continue until digit sum <= target. TutorialsPoint - Minimum Addition to Make Integer Beautiful | Greedy Digit Rounding Approach
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