LeetCode 题解工作台

哈沙德数

如果一个整数能够被其各个数位上的数字之和整除,则称之为 哈沙德数 (Harshad number)。给你一个整数 x 。如果 x 是 哈沙德数 ,则返回 x 各个数位上的数字之和,否则,返回 -1 。 示例 1: 输入: x = 18 输出: 9 解释: x 各个数位上的数字之和为 9 。 18 能…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们可以通过模拟的方法,计算出 的各个数位上的数字之和,记为 。如果 能被 整除,则返回 ,否则返回 。 时间复杂度 $O(\log x)$,其中 是输入的整数。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

如果一个整数能够被其各个数位上的数字之和整除,则称之为 哈沙德数(Harshad number)。给你一个整数 x 。如果 x哈沙德数 ,则返回 x 各个数位上的数字之和,否则,返回 -1

 

示例 1:

输入: x = 18

输出: 9

解释:

x 各个数位上的数字之和为 918 能被 9 整除。因此 18 是哈沙德数,答案是 9

示例 2:

输入: x = 23

输出: -1

解释:

x 各个数位上的数字之和为 523 不能被 5 整除。因此 23 不是哈沙德数,答案是 -1

 

提示:

  • 1 <= x <= 100
lightbulb

解题思路

方法一:模拟

我们可以通过模拟的方法,计算出 xx 的各个数位上的数字之和,记为 ss。如果 xx 能被 ss 整除,则返回 ss,否则返回 1-1

时间复杂度 O(logx)O(\log x),其中 xx 是输入的整数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
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
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

哈沙德数题解:数学·driven | LeetCode #3099 简单