150強訪談簡單

反轉整數

“反向整數”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個有符號 32 位元整數 x,傳回 x 的數字反轉。如果反轉 x 導致值超出有符號 32 位元整數範圍 [-2^31, 2^31 - 1],則傳回 0。

假設環境不允許您儲存 64 位元整數(有符號或無符號)。

寫一個函數 reverse(x: int) -> int

約束條件
  • -2^31 <= x <= 2^31 - 1

範例

Example 1
Input
x = 123
Output
321
Explanation

Reversing 123 gives 321.

Example 2
Input
x = -123
Output
-321
Explanation

Reversing -123 gives -321.

Example 3
Input
x = 120
Output
21
Explanation

Reversing 120 gives 021, which is 21.

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

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