LeetCode 题解工作台
求出数字答案
给你三个 正 整数 num1 , num2 和 num3 。 数字 num1 , num2 和 num3 的数字答案 key 是一个四位数,定义如下: 一开始,如果有数字 少于 四位数,给它补 前导 0 。 答案 key 的第 i 个数位( 1 )为 num1 , num2 和 num3 第 i 个…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们可以直接模拟这个过程,定义一个变量 用于存储答案,定义一个变量 用于表示当前位数,其中 $\textit{k} = 1$ 表示个位数,而 $\textit{k} = 10$ 表示十位数,以此类推。 我们从个位数开始,对于每一位,我们分别计算 , 和 的当前位数,取三者的最小值,然后将这个最小值乘以 加到答案上。然后将 乘以 10,继续计算下一位。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你三个 正 整数 num1 ,num2 和 num3 。
数字 num1 ,num2 和 num3 的数字答案 key 是一个四位数,定义如下:
- 一开始,如果有数字 少于 四位数,给它补 前导 0 。
- 答案
key的第i个数位(1 <= i <= 4)为num1,num2和num3第i个数位中的 最小 值。
请你返回三个数字 没有 前导 0 的数字答案。
示例 1:
输入:num1 = 1, num2 = 10, num3 = 1000
输出:0
解释:
补前导 0 后,num1 变为 "0001" ,num2 变为 "0010" ,num3 保持不变,为 "1000" 。
- 数字答案
key的第1个数位为min(0, 0, 1)。 - 数字答案
key的第2个数位为min(0, 0, 0)。 - 数字答案
key的第3个数位为min(0, 1, 0)。 - 数字答案
key的第4个数位为min(1, 0, 0)。
所以数字答案为 "0000" ,也就是 0 。
示例 2:
输入: num1 = 987, num2 = 879, num3 = 798
输出:777
示例 3:
输入:num1 = 1, num2 = 2, num3 = 3
输出:1
提示:
1 <= num1, num2, num3 <= 9999
解题思路
方法一:模拟
我们可以直接模拟这个过程,定义一个变量 用于存储答案,定义一个变量 用于表示当前位数,其中 表示个位数,而 表示十位数,以此类推。
我们从个位数开始,对于每一位,我们分别计算 , 和 的当前位数,取三者的最小值,然后将这个最小值乘以 加到答案上。然后将 乘以 10,继续计算下一位。
最后返回答案即可。
时间复杂度 ,空间复杂度 。
class Solution:
def generateKey(self, num1: int, num2: int, num3: int) -> int:
ans, k = 0, 1
for _ in range(4):
x = min(num1 // k % 10, num2 // k % 10, num3 // k % 10)
ans += x * k
k *= 10
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) since there are exactly four digits to process. Space complexity is O(1) as only fixed-length strings and the resulting integer are stored. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you correctly handling numbers with fewer than four digits by padding zeros?
- question_mark
Can you explain how digit comparison at each position ensures correctness?
- question_mark
How would your solution scale if numbers had more than four digits?
常见陷阱
外企场景- error
Forgetting to pad numbers leads to misaligned digit comparisons.
- error
Returning a string instead of an integer may produce leading zeros incorrectly.
- error
Assuming input numbers always have identical digit lengths without normalization.
进阶变体
外企场景- arrow_right_alt
Compute the key for n numbers instead of three, still using digit-by-digit comparison.
- arrow_right_alt
Return the key as a string preserving all leading zeros instead of converting to integer.
- arrow_right_alt
Use a modulus and division approach to extract digits instead of string conversion for comparison.