Python 基礎知識簡單

將給定整數中的所有 0 替換為 1

「將給定整數中的所有 0 替換為 1」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 replace_zeros(n) ,它接受一個正整數 n 並傳回一個新整數,其中 n 中的每個數字「0」都已替換為「1」。

例如,如果 n = 102030,則結果應為 112131(每個 0 變為 1)。

約束條件
  • 1 <= n <= 10^9

範例

Example 1
Input
replace_zeros(102030)
Output
112131
Explanation

The digits of 102030 are 1,0,2,0,3,0. Replacing each 0 with 1 gives 1,1,2,1,3,1 = 112131.

Example 2
Input
replace_zeros(1000)
Output
1111
Explanation

1,0,0,0 becomes 1,1,1,1 = 1111.

Example 3
Input
replace_zeros(123)
Output
123
Explanation

No zeros in 123, so it remains unchanged.

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 資源

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