Implement the function double myPow(double x, int n) that calculates x raised to the power n (i.e., x^n). Be careful of overflow for large values of n.
Q: Can n be negative?
A: Yes, n can be negative, and in such cases, we need to return (1 / x^{-n}).
Q: What is the range for x and n?
A: x is a double, and n is a 32-bit signed integer.
Q: How should we handle edge cases, like ( x = 0 ) or ( n = 0 )? A: Any number raised to 0 is 1. (0^0 \text{ is traditionally considered to be 1}).
Let’s write the code using an iterative approach with Exponentiation by Squaring for better efficiency.
def myPow(x: float, n: int) -> float:
if n == 0:
return 1.0
if n < 0:
x = 1 / x
n = -n
result = 1.0
current_product = x
while n > 0:
if n % 2 == 1:
result *= current_product
current_product *= current_product
n //= 2
return result
This approach ensures that the function efficiently handles large values of n, including negative powers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?