LeetCode 题解工作台

各位相加

给定一个非负整数 num ,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。 示例 1: 输入: num = 38 输出: 2 解释: 各位相加的过程为 : 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 由于 2 是一位数,所以返回 2。 示例 2: 输入:…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·结合·模拟

bolt

答案摘要

class Solution: def addDigits(self, num: int) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个非负整数 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) 时间复杂度内解决这个问题吗?

lightbulb

解题思路

方法一

1
2
3
4
class Solution:
    def addDigits(self, num: int) -> int:
        return 0 if num == 0 else (num - 1) % 9 + 1
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

各位相加题解:数学·结合·模拟 | LeetCode #258 简单