Use binary exponentiation: square when the exponent is even, multiply when odd. Handle negative exponents by inverting x.
Here's the solution:
function myPow(x, n):
if n < 0:
x = 1 / x
n = -n
result = 1
while n > 0:
if n is odd:
result = result * x
x = x * x
n = n / 2 (integer division)
return result
time, space.