LeetCode 题解工作台
美丽整数的最小增量
给你两个正整数 n 和 target 。 如果某个整数每一位上的数字相加小于或等于 target ,则认为这个整数是一个 美丽整数 。 找出并返回满足 n + x 是 美丽整数 的最小非负整数 x 。生成的输入保证总可以使 n 变成一个美丽整数。 示例 1: 输入: n = 16, target =…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们定义函数 表示一个整数 的每一位数字之和,那么题目求的是 $f(n + x) \leq target$ 的最小非负整数 。 如果 $y = n+x$ 的每一位数字之和大于 ,那么我们可以循环通过以下操作,将 的每一位数字之和减小到小于等于 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你两个正整数 n 和 target 。
如果某个整数每一位上的数字相加小于或等于 target ,则认为这个整数是一个 美丽整数 。
找出并返回满足 n + x 是 美丽整数 的最小非负整数 x 。生成的输入保证总可以使 n 变成一个美丽整数。
示例 1:
输入:n = 16, target = 6 输出:4 解释:最初,n 是 16 ,且其每一位数字的和是 1 + 6 = 7 。在加 4 之后,n 变为 20 且每一位数字的和变成 2 + 0 = 2 。可以证明无法加上一个小于 4 的非负整数使 n 变成一个美丽整数。
示例 2:
输入:n = 467, target = 6 输出:33 解释:最初,n 是 467 ,且其每一位数字的和是 4 + 6 + 7 = 17 。在加 33 之后,n 变为 500 且每一位数字的和变成 5 + 0 + 0 = 5 。可以证明无法加上一个小于 33 的非负整数使 n 变成一个美丽整数。
示例 3:
输入:n = 1, target = 1 输出:0 解释:最初,n 是 1 ,且其每一位数字的和是 1 ,已经小于等于 target 。
提示:
1 <= n <= 10121 <= target <= 150- 生成的输入保证总可以使
n变成一个美丽整数。
解题思路
方法一:贪心
我们定义函数 表示一个整数 的每一位数字之和,那么题目求的是 的最小非负整数 。
如果 的每一位数字之和大于 ,那么我们可以循环通过以下操作,将 的每一位数字之和减小到小于等于 :
- 找到 的最低位的非零数字,将其减小到 ,并将其高一位的数字加 ;
- 更新 ,继续上述操作,直到 的每一位数字之和小于等于 。
循环结束,返回 即可。
我们可以举个例子,假设 , ,那么 的变化过程如下:
时间复杂度 ,其中 给题目给定的整数。空间复杂度 。
class Solution:
def makeIntegerBeautiful(self, n: int, target: int) -> int:
def f(x: int) -> int:
y = 0
while x:
y += x % 10
x //= 10
return y
x = 0
while f(n + x) > target:
y = n + x
p = 10
while y % 10 == 0:
y //= 10
p *= 10
x = (y // 10 + 1) * p - n
return x
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Interviewee demonstrates understanding of digit-based greedy strategies.
- question_mark
Candidate identifies the importance of considering each digit independently.
- question_mark
Solver maintains efficiency with a logarithmic approach to the number of digits.
常见陷阱
外企场景- error
Forgetting to consider the sum of digits at each place value independently.
- error
Not minimizing the addition when examining possible values for x.
- error
Misunderstanding the problem constraints and incorrectly assuming the addition could be larger.
进阶变体
外企场景- arrow_right_alt
What if the target were negative or zero?
- arrow_right_alt
What if n is very large, approaching the upper limits of the constraint?
- arrow_right_alt
What if the target was set to be much larger than the sum of digits of n?