Pow(x, n)
Return x raised to the power n.
x is a real number and n is a signed 32-bit integer, so n reaches -2^31 and 2^31 - 1. A negative n means the reciprocal, x^n = 1 / x^|n|, and n = 0 returns 1. Because x is never 0, the reciprocal is always defined. The result is an IEEE-754 double, so very large exponents legitimately produce Infinity and very small ones underflow to 0.
Examples
Input: [2,10]
Output: 1024
Input: [2,-2]
Output: 0.25
Hints
Consider using recursion to break down the exponentiation into smaller subproblems, leveraging the mathematical property that \(x^n = (x^{n/2})^2\) when \(n\) is even.
For negative exponents, first compute the positive exponent and then take the reciprocal of the result to handle the inversion efficiently.
Optimize the base case to return 1 when the exponent is 0, and handle the case where the exponent is odd by multiplying the result by \(x\) once more after the recursive step.
Related Problems
Pow(x, n)
Return x raised to the power n.