We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Addition to Make Integer Beautiful

Difficulty: Medium


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 increment n by a non-negative integer x until the digit sum is less than or equal to target.
  • 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:

  1. Initialize x to 0.
  2. While the digit sum of n + x is greater than target, increment x and check again.
  3. 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.


Code Solutions

def digit_sum(num):
    return sum(int(d) for d in str(num))

def minimumAddition(n, target):
    x = 0
    while digit_sum(n + x) > target:
        x += 1
    return x
← Back to All Questions