Minimum Addition to Make Integer Beautiful

Problem Description

Ah, the age-old quest for beauty! No, not the kind that involves makeup or fancy clothes, but the mathematical kind. The problem at hand is to transform an integer into a “beautiful” one. What does that mean, you ask? Well, it means ensuring that the sum of its digits does not exceed a given target.

Imagine you have a friend who insists on counting calories. You know, the type who will add up every crumb of food they consume. Now, if their calorie count exceeds their target, they might just throw in a salad to balance things out. Similarly, in this problem, we need to add the least amount possible to our integer to keep the sum of its digits within the target.

So, if you have a number like 123 and a target of 5, you might need to add a little something to make it “beautiful.” Because who wants to be ugly, right?

Code Solution


class Solution:
    def makeIntegerBeautiful(self, n: int, target: int) -> int:
        ans = 0
        power = 1

        while sum(map(int, str(n))) > target:
            ans += power * (10 - n % 10)
            n = n // 10 + 1
            power *= 10

        return ans

Approach Explanation

The code works by continuously checking if the sum of the digits of n exceeds the target. If it does, it calculates how much needs to be added to make the last digit a zero (because zeros are the best at keeping things low-key). It then reduces n by effectively “turning off” the last digit and moving to the next one. This process continues until the sum of the digits is within the target.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(log n)
Space Complexity O(1)

Real-World Example

Think of it like trying to fit into your favorite pair of jeans after the holidays. If you’ve indulged a bit too much, you might need to “add” some time at the gym to get back to your target weight. Similarly, in this problem, we are adding the least amount to our integer to ensure it fits within the “beautiful” range of digit sums.

Similar Problems

If you enjoyed this problem, you might also like these: