Python 基礎知識中等

使用遞歸計算數字的冪

「使用遞歸的數字冪」問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 power(base, exp),使用遞歸計算 baseexp 次方。此函數應採用兩個整數 baseexp 作為輸入,並以整數形式傳回結果。假設 exp 始終為非負數。

約束條件
  • 0 <= exp <= 20
  • -10 <= base <= 10

範例

Example 1
Input
base = 2, exp = 10
Output
1024
Explanation

2^10 = 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 1024

Example 2
Input
base = 3, exp = 4
Output
81
Explanation

3^4 = 3 * 3 * 3 * 3 = 81

Example 3
Input
base = 5, exp = 0
Output
1
Explanation

Any number raised to the power 0 is 1

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

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