Leetcode 2457: Minimum Addition to Make Integer Beautiful

grid47
grid47
Exploring patterns and algorithms
Mar 6, 2024 5 min read

Given a positive integer n and a target sum, the task is to find the smallest non-negative integer x such that the sum of the digits of n + x is less than or equal to the given target. The solution is guaranteed to always be possible for the given constraints.
Problem
Approach
Steps
Complexity
Input: You are given two integers, n and target, where n is a positive integer and target is the maximum allowed sum of the digits of n + x.
Example: n = 25, target = 10
Constraints:
• 1 <= n <= 10^12
• 1 <= target <= 150
Output: Return the minimum non-negative integer x such that the sum of the digits of n + x is less than or equal to target. The result should be a single integer.
Example: For n = 25 and target = 10, the output will be 5.
Constraints:
Goal: The goal is to find the smallest integer x such that the sum of the digits of n + x is less than or equal to the target.
Steps:
• 1. Calculate the sum of digits of n.
• 2. If the sum of digits of n is already less than or equal to target, return 0.
• 3. Otherwise, find the smallest x by incrementing n in such a way that the sum of the digits becomes less than or equal to target.
Goal: The solution should work efficiently even for large values of n (up to 10^12).
Steps:
• The problem is guaranteed to have a solution.
Assumptions:
• It is always possible to find a non-negative x such that n + x becomes beautiful.
Input: n = 25, target = 10
Explanation: Initially, the sum of the digits of n (25) is 2 + 5 = 7, which is less than target. After adding 5 to n, we get 30, and the sum of digits becomes 3 + 0 = 3, which is still less than target.

Input: n = 467, target = 6
Explanation: The sum of digits of n (467) is 4 + 6 + 7 = 17, which is greater than target. After adding 33, n becomes 500, and the sum of digits is 5 + 0 + 0 = 5, which satisfies the target.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus