Python 基礎知識簡單

求x位出現的次數

「尋找 x 數字出現的次數」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 count_digit(n, x),它接受一個非負整數 n 和一個數字 x (0-9),並傳回數字 xn 中出現的次數。

例如,在數字 122333 中,數字 3 出現了 3 次。

約束條件
  • 0 <= n <= 10^9
  • 0 <= x <= 9

範例

Example 1
Input
count_digit(122333, 3)
Output
3
Explanation

The digits of 122333 are 1,2,2,3,3,3. The digit 3 appears 3 times.

Example 2
Input
count_digit(1000, 0)
Output
3
Explanation

The digits of 1000 are 1,0,0,0. The digit 0 appears 3 times.

Example 3
Input
count_digit(12345, 6)
Output
0
Explanation

The digit 6 does not appear in 12345.

Need a Hint?
考慮使用特定於數字的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。