[LeeCode] 50. Pow(x, n) python3
题目描述
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。
1.python递归1
class Solution(object): def myPow(self, x, n): if n == 0 or x == 1 : return 1 if n == 1: return x if n == -1: return 1 / x return self.myPow(x, n % 2) * self.myPow(x * x, n//2)
2.python递归2
class Solution(object): def myPow(self, x, n): if n == 0 or x == 1: return 1 elif n < 0: x = 1/x n = -n return self.myPow(x*x, n/2) if n % 2 == 0 else x * self.myPow(x*x, n//2)
3.python普通算法
class Solution: def myPow(self, x: float, n: int) -> float: if n == 0 or x == 1: return 1 result = 1.0 while 0 != n: if n % 2 != 0: result *= x if n == 1 or n == -1: return 1/result if n <0 else result n = int(n/2) x *= x
#return 1/result if n <0 else result
4.python超时算法
class Solution: def myPow(self, x: float, n: int) -> float: if n == 0 or x == 1:return 1 elif n < 0: x = 1/x n = -n a = x for i in range(n -1): x *= a return x