LeetCode 题解工作台
哈沙德数
如果一个整数能够被其各个数位上的数字之和整除,则称之为 哈沙德数 (Harshad number)。给你一个整数 x 。如果 x 是 哈沙德数 ,则返回 x 各个数位上的数字之和,否则,返回 -1 。 示例 1: 输入: x = 18 输出: 9 解释: x 各个数位上的数字之和为 9 。 18 能…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们可以通过模拟的方法,计算出 的各个数位上的数字之和,记为 。如果 能被 整除,则返回 ,否则返回 。 时间复杂度 $O(\log x)$,其中 是输入的整数。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
如果一个整数能够被其各个数位上的数字之和整除,则称之为 哈沙德数(Harshad number)。给你一个整数 x 。如果 x 是 哈沙德数 ,则返回 x 各个数位上的数字之和,否则,返回 -1 。
示例 1:
输入: x = 18
输出: 9
解释:
x 各个数位上的数字之和为 9 。18 能被 9 整除。因此 18 是哈沙德数,答案是 9 。
示例 2:
输入: x = 23
输出: -1
解释:
x 各个数位上的数字之和为 5 。23 不能被 5 整除。因此 23 不是哈沙德数,答案是 -1 。
提示:
1 <= x <= 100
解题思路
方法一:模拟
我们可以通过模拟的方法,计算出 的各个数位上的数字之和,记为 。如果 能被 整除,则返回 ,否则返回 。
时间复杂度 ,其中 是输入的整数。空间复杂度 。
class Solution:
def sumOfTheDigitsOfHarshadNumber(self, x: int) -> int:
s, y = 0, x
while y:
s += y % 10
y //= 10
return s if x % s == 0 else -1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for understanding of basic math operations and modular arithmetic.
- question_mark
Should be able to identify the simple approach of summing digits.
- question_mark
Test if candidate can efficiently implement digit extraction and divisibility check.
常见陷阱
外企场景- error
Forgetting to handle the case where the sum of digits does not divide `x` properly.
- error
Using a string-based approach for digit extraction instead of mathematical operations.
- error
Confusing the sum of digits with the actual number itself and not performing the divisibility check correctly.
进阶变体
外企场景- arrow_right_alt
Try the problem for larger numbers to test efficiency.
- arrow_right_alt
Modify the problem to check if a number is divisible by the product of its digits instead of the sum.
- arrow_right_alt
Consider edge cases like very small numbers or numbers with repeating digits.