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

LeetCode 3908: Valid Digit Number

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

基本資料
#

難易度: easy 第一次嘗試:2026-04-25

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

解題思路
#

兩個條件都是字串操作:

  • 至少出現一次 x:str(x) in s。
  • 不是以 x 開頭:not s.startswith(str(x))。

我的解法
#

class Solution:
    def validDigit(self, n: int, x: int) -> bool:
        s = str(n)
        return str(x) in s and not s.startswith(str(x))

複雜度
#

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

要特別避免的錯誤
#

  • x 是整數,要先轉成字串才能跟字串比較。

面試口說整理
#

把 n 轉成字串,檢查裡面有 x,而且第一個字元不是 x。時間 O(d)。

相關文章

LeetCode 976: Largest Perimeter Triangle
·1 分鐘
LeetCode Easy Math Greedy Sorting Geometry Array
LeetCode 976 解題筆記:排序後,從最大的開始看連續的三條邊,a + b > c 第一次成立就是最大周長
LeetCode 2269: Find the K-Beauty of a Number
·1 分鐘
LeetCode Easy Sliding-Window Math String
LeetCode 2269 解題筆記:把數字轉成字串,枚舉每個長度 k 的子字串;0 不能當除數
LeetCode 1281: Subtract the Product and Sum of Digits of an Integer
·1 分鐘
LeetCode Easy Math
LeetCode 1281 解題筆記:一次走過所有位數,同時累積積與和,回傳積減和
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 的位數乘上它的位值就是一個分量,從高位到低位輸出