[50][中等][二分] Pow(x, n)
题目描述
输入: 2.00000, 10
输出: 1024.00000输入: 2.10000, 3
输出: 9.26100输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25解题思路
递归
最后更新于
输入: 2.00000, 10
输出: 1024.00000输入: 2.10000, 3
输出: 9.26100输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25最后更新于
class Solution:
def myPow(self, x: float, n: int) -> float:
def dfs(exp):
if exp == 0:
return 1.0
odd, half = exp % 2, exp // 2
y = dfs(half)
return y * y if not odd else y * y * x
return dfs(n) if n >= 0 else 1.0 / dfs(-n)