原题
https://leetcode.cn/problems/powx-n/description/
思路
递归
复杂度
时间:O(log(n))
空间:O(1)
Python代码
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
elif n == 1:
return x
elif n < 0:
return 1 / self.myPow(x, -n)
elif n % 2 != 0:
return self.myPow(x, n - 1) * x
else:
root = self.myPow(x, n // 2)
return root * root
Go代码
func myPow(x float64, n int) float64 {
if n == 0 {
return 1
} else if n == 1 {
return x
} else if n < 0 {
return 1 / myPow(x, -n)
} else if n%2 != 0 {
return myPow(x, n-1) * x
} else {
root := myPow(x, n/2)
return root * root
}
}
332

被折叠的 条评论
为什么被折叠?



