Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2457. Minimum Addition to Make Integer Beautiful

MathGreedy

Explanation

To solve this problem, we need to find the minimum non-negative integer x such that n + x is beautiful. We can do this by calculating the sum of the digits of n and then determining how much we need to add to make the sum less than or equal to the target.

We can find the sum of the digits of a number by repeatedly dividing the number by 10 and summing the remainders. Once we have the sum of the digits of n, we can calculate how much we need to add by subtracting the target from the sum. If the sum is already less than or equal to the target, we don't need to add anything.

class Solution {
    public int minAddToMakeIntegerBeautiful(int n, int target) {
        int sum = digitSum(n);
        return Math.max(0, target - sum);
    }

    private int digitSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.