LeetCode 题解工作台

判断整除性

给你一个正整数 n 。请判断 n 是否可以被以下两值之和 整除 : n 的 数字和 (即其各个位数之和)。 n 的 数字积 (即其各个位数之积)。 如果 n 能被该和整除,返回 true ;否则,返回 false 。 示例 1: 输入: n = 99 输出: true 解释: 因为 99 可以被其数…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们可以遍历整数 的每一位数字,计算出数字和 和数字积 。最后判断 是否能被 $s + p$ 整除。 时间复杂度 $O(\log n)$,其中 为整数 的值。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n。请判断 n 是否可以被以下两值之和 整除

  • n 的 数字和(即其各个位数之和)。

  • n 的 数字积(即其各个位数之积)。

如果 n 能被该和整除,返回 true;否则,返回 false

 

示例 1:

输入: n = 99

输出: true

解释:

因为 99 可以被其数字和 (9 + 9 = 18) 与数字积 (9 * 9 = 81) 之和 (18 + 81 = 99) 整除,因此输出为 true。

示例 2:

输入: n = 23

输出: false

解释:

因为 23 无法被其数字和 (2 + 3 = 5) 与数字积 (2 * 3 = 6) 之和 (5 + 6 = 11) 整除,因此输出为 false。

 

提示:

  • 1 <= n <= 106
lightbulb

解题思路

方法一:模拟

我们可以遍历整数 nn 的每一位数字,计算出数字和 ss 和数字积 pp。最后判断 nn 是否能被 s+ps + p 整除。

时间复杂度 O(logn)O(\log n),其中 nn 为整数 nn 的值。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def checkDivisibility(self, n: int) -> bool:
        s, p = 0, 1
        x = n
        while x:
            x, v = divmod(x, 10)
            s += v
            p *= v
        return n % (s + p) == 0
speed

复杂度分析

指标
时间complexity is O(d) where d is the number of digits in n since each digit is processed once. Space complexity is O(1) for integer operations, or O(d) if storing digits in an array.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for direct computation of digit sum and product without iterating over ranges.

  • question_mark

    Expect handling of zeros in product calculations.

  • question_mark

    Be prepared to explain why adding sum and product ensures divisibility correctness.

warning

常见陷阱

外企场景
  • error

    Ignoring zeros in the digit product, which may incorrectly return false.

  • error

    Mistaking sum of digits for sum plus product in the final divisibility check.

  • error

    Using loops over all numbers up to n instead of digit-level computation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Check divisibility by sum minus product of digits.

  • arrow_right_alt

    Determine if n is divisible by sum of squares of digits plus their product.

  • arrow_right_alt

    Apply the same logic to base-k numbers instead of decimal digits.

help

常见问题

外企场景

判断整除性题解:数学·driven | LeetCode #3622 简单