One line slick solution:
return x**n
Run Time is 52 ms.
Normal solution is not timing one by one, which is two slow. Recursion is a good approach, but some cases need to be considered: n is negative and n is odd.
Solution:
# T:O(lgn) S:O(lgn)
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def myPow(self, x, n):
if n < 0:
return 1 / self.powRecu(x, -n)
return self.powRecu(x, n)
def powRecu(self, x, n):
if n == 0:
return 1.0
if n % 2 == 0:
return self.powRecu(x * x, n / 2)
else:
return x * self.powRecu(x * x, n / 2)
Run Time: 56 ms
No comments:
Post a Comment