Hi,
I am trying to find Power(x, n) when n is large by recursive binary division on n. I tried two methods, the first of which has an overflow error but the second works well. Why? What’s the difference?
First:
class Solution50:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n == 1:
return x
if n < 0 :
return 1/self.myPow(x, -n)
if n % 2 == 0:
return (self.myPow(x**2, n//2))
if n % 2 == 1:
return x * (self.myPow(x**2, n//2))
sol50 = Solution50()
sol50.myPow(2.00, -2147483648)
Second:
class Solution50f:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1.0
elif n < 0:
return 1 / self.myPow(x, -n)
elif n % 2:
return self.myPow(x * x, n // 2) * x
else:
return self.myPow(x * x, n // 2)
sol50f = Solution50f()
sol50f.myPow(2.00, -2147483648)