Reputation: 91
I am implementing the power function and the following works. However, when I replace self.myPow(x*x,n/2)
with self.myPow(x,n/2)**2
, I got OverflowError: (34, 'Numerical result out of range'). I thought these two equivalent, what did I miss?
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n==0:
return 1
elif n==1:
return x
elif n>=1 and n%2==0:
return self.myPow(x*x,n/2)
elif n>=1 and n%2==1:
return self.myPow(x*x,(n-1)/2) * x
else:
return 1/self.myPow(x,-n)
Upvotes: -2
Views: 16