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

LeetCode 1281: Subtract the Product and Sum of Digits of an Integer

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

基本資料
#

難易度: easy 第一次嘗試:2025-12-23

  • 提交紀錄:Accepted(C++,一次通過)

解題思路
#

走過每個位數,積從 1 開始乘、和從 0 開始加,回傳 積 - 和。

我的解法
#

我當時用 C++ 的 to_string 走位數,這裡放等價的 Python:

class Solution:
    def subtractProductAndSum(self, n: int) -> int:
        product, total = 1, 0
        while n:
            d = n % 10
            product *= d
            total += d
            n //= 10
        return product - total

複雜度
#

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

要特別避免的錯誤
#

  • 積的初始值是 1,不是 0。

面試口說整理
#

用 % 10 一位一位拿出來,同時累積積和和,最後相減。時間 O(d)。

相關文章

LeetCode 1512: Number of Good Pairs
·1 分鐘
LeetCode Easy Math Hash-Table Counting Array
LeetCode 1512 解題筆記:邊掃邊數,每個數可以跟前面每個相同的數配一對,答案加上目前的出現次數
LeetCode 2469: Convert the Temperature
·1 分鐘
LeetCode Easy Math
LeetCode 2469 解題筆記:直接套公式,Kelvin = C + 273.15,Fahrenheit = C × 1.8 + 32
LeetCode 3697: Compute Decimal Representation
·1 分鐘
LeetCode Easy Math Array
LeetCode 3697 解題筆記:每個非 0 的位數乘上它的位值就是一個分量,從高位到低位輸出
LeetCode 3550: Smallest Index With Digit Sum Equal to Index
·1 分鐘
LeetCode Easy Math Array
LeetCode 3550 解題筆記:由小到大檢查每個 index,算位數和,第一個相等的就是答案
LeetCode 1979: Find Greatest Common Divisor of Array
·1 分鐘
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 解題筆記:找出最小值和最大值,用輾轉相除法算 GCD
LeetCode 1486: XOR Operation in an Array
·1 分鐘
LeetCode Easy Math Bit-Manipulation
LeetCode 1486 解題筆記:依定義產生 start + 2i,逐一 XOR 起來