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

LeetCode 3697: Compute Decimal Representation

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

基本資料
#

難易度: easy 第一次嘗試:2025-09-28

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

解題思路
#

一個分量只能是「一個 1~9 的位數 × 10 的次方」,所以每一個非 0 的位數剛好對應一個分量,例如 537 = 500 + 30 + 7。0 的位數不用分量。要用最少個,就是每個非 0 位數各一個,不能再少(每個分量只能貢獻一個位數)。

用 % 10 從低位拿位數,同時記錄位值 place,最後反轉成由大到小。

我的解法
#

class Solution:
    def decimalRepresentation(self, n: int) -> List[int]:
        res = []
        place = 1
        while n:
            d = n % 10
            if d:
                res.append(d * place)
            n //= 10
            place *= 10
        return res[::-1]                   # 由大到小

我當時用字串 f"{r}{'0' * zeros}" 組出分量,效果一樣,乘上 place 比較直接。

複雜度
#

時間 O(d),d 是位數,空間 O(d)。

要特別避免的錯誤
#

  • 位數是 0 時不要放進答案。
  • 從低位拿出來的順序是由小到大,要反轉。

面試口說整理
#

每個非 0 的位數乘上它的位值就是一個分量,而且每個分量只能代表一個位數,所以這就是最少的。我從低位用 % 10 拿位數、跳過 0,最後反轉成由大到小。時間 O(d)。

相關文章

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 1304: Find N Unique Integers Sum up to Zero
·1 分鐘
LeetCode Easy Math Array
LeetCode 1304 解題筆記:放 1..n/2 和它們的相反數,兩兩抵銷;n 是奇數時再加一個 0
LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 989: Add to Array-Form of Integer
·1 分鐘
LeetCode Easy Array Math
LeetCode 989 解題筆記:把 k 當成進位,從陣列最後一位往前加,k 還沒用完就繼續往前補位
LeetCode 908: Smallest Range I
·1 分鐘
LeetCode Easy Array Math
LeetCode 908 解題筆記:最大值往下調 k、最小值往上調 k,答案是 max(0, max - min - 2k)