50. Pow(x, n)
Implement pow(x, n).
Solution:
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n < 0:
if x == 0:
raise ZeroDivisionError('0.0 cannot be raised to a negative power')
return 1 / self.myPow(x, -n)
if n == 0:
return 1
val = self.myPow(x, n / 2)
if n % 2 == 1:
return x * val * val
return val * val