LeetCode 题解工作台
各位相加
给定一个非负整数 num ,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。 示例 1: 输入: num = 38 输出: 2 解释: 各位相加的过程为 : 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 由于 2 是一位数,所以返回 2。 示例 2: 输入:…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·模拟
答案摘要
class Solution: def addDigits(self, num: int) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路
题目描述
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。
示例 1:
输入: num =38输出: 2 解释: 各位相加的过程为: 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 由于2是一位数,所以返回 2。
示例 2:
输入: num = 0 输出: 0
提示:
0 <= num <= 231 - 1
进阶:你可以不使用循环或者递归,在 O(1) 时间复杂度内解决这个问题吗?
解题思路
方法一
class Solution:
def addDigits(self, num: int) -> int:
return 0 if num == 0 else (num - 1) % 9 + 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate should show understanding of basic digit operations and how to optimize them.
- question_mark
Look for recognition of number properties like digital roots and their use in optimization.
- question_mark
Expect exploration of both brute force and efficient approaches, demonstrating a clear trade-off analysis.
常见陷阱
外企场景- error
Misunderstanding the problem and applying unnecessary loops or calculations.
- error
Not recognizing the mathematical shortcut using modulo operations to directly compute the result.
- error
Forgetting edge cases like `num = 0` or not handling the case where `num % 9 == 0` correctly.
进阶变体
外企场景- arrow_right_alt
Apply the same concept to larger numbers where the number of iterations grows.
- arrow_right_alt
Solve the problem using recursion instead of iteration.
- arrow_right_alt
Handle a list of numbers and apply the same digit-sum reduction approach.