↓快轉到主要內容
  1. LeetCode/

LeetCode 3622: Check Divisibility by Digit Sum and Product

·1 分鐘· ·
LeetCode Easy Math
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-07-20

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

n 要能被「位數和 + 位數積」整除,也就是 n % (sum + product) == 0。位數和至少是 1,所以除數不會是 0。

我的嘗試
#

第一版寫成 (product + sum) % n == 0,方向反了。例如 n = 2:和是 2、積是 2,2 % 4 = 2,答案是 False;這版算 4 % 2 = 0,回傳 True。

正確解法
#

from math import prod

class Solution:
    def checkDivisibility(self, n: int) -> bool:
        digits = [int(c) for c in str(n)]
        return n % (sum(digits) + prod(digits)) == 0

複雜度
#

時間 O(d),空間 O(d)。

要特別避免的錯誤
#

  • 「n 被 x 整除」是 n % x == 0,不是 x % n == 0。

面試口說整理
#

我把 n 拆成位數,算和與積,檢查 n 除以兩者相加的餘數是不是 0。時間 O(d)。

相關文章

LeetCode 3536: Maximum Product of Two Digits
·1 分鐘
LeetCode Easy Math Sorting
LeetCode 3536 解題筆記:找出最大和第二大的位數相乘;找到新的最大值時,舊的最大值要移到第二名
LeetCode 3492: Maximum Containers on a Ship
·1 分鐘
LeetCode Easy Math
LeetCode 3492 解題筆記:最多 n² 個格子,重量最多放 maxWeight // w 個,取兩者較小值;用整數除法
LeetCode 1103: Distribute Candies to People
·1 分鐘
LeetCode Easy Math Simulation
LeetCode 1103 解題筆記:模擬一輪一輪發糖果,第 i 次發 i + 1 顆,不夠時把剩下的全給目前這個人
LeetCode 1137: N-th Tribonacci Number
·1 分鐘
LeetCode Easy Math Dynamic-Programming Memoization
LeetCode 1137 解題筆記:跟 Fibonacci 一樣,用三個變數滾動;小心 T0 = 0、T1 = T2 = 1 的起始值和迴圈範圍
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 1025: Divisor Game
·1 分鐘
LeetCode Easy Math Dynamic-Programming Brainteaser Game-Theory
LeetCode 1025 解題筆記:dp[i] = 存在 i 的因數 x 讓 dp[i - x] 是輸;觀察後答案就是 n 是偶數