See Code
O(logn) ~ O(log^2(n))
Iterative:
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
ans = 1.0
m = abs(n)
while m:
if m & 1:
ans *= x
m >>= 1
x *= x
return ans if n > 0 else 1/ans
Recrusive:
class Solution:
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if not n:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
if n & 1:
return x * self.myPow(x, n-1)
return self.myPow(x*x, n >> 1)