Power Function

Easy~15 min

Given two non-negative integers base and exp, compute base^exp (base raised to the power of exp) using recursion.

Use fast exponentiation (also called exponentiation by squaring):

  • If exp is 0, return 1
  • If exp is even, power(base, exp) = power(base, exp / 2) * power(base, exp / 2)
  • If exp is odd, power(base, exp) = base * power(base, exp - 1)

To avoid redundant computation, compute power(base, exp / 2) once and square the result.

You must solve this problem recursively — do not use loops or built-in power functions.

Examples

Example 1
Input: base = 2, exp = 10
Output: 1024
Explanation: 2^10 = 1024.
Example 2
Input: base = 3, exp = 0
Output: 1
Explanation: Any number raised to the power of 0 is 1.
Example 3
Input: base = 5, exp = 3
Output: 125
Explanation: 5^3 = 5 * 5 * 5 = 125.

Constraints

  • 0 <= base <= 100
  • 0 <= exp <= 30
  • The result fits in a 64-bit integer.
  • You must use recursion (no loops or built-in power functions).
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run