题目
实现 pow(x, n)
,即计算 x 的 n 次幂函数。
示例 1:
输入: 2.00000, 10
输出: 1024.00000
示例 2:
输入: 2.00000, -2
输出: 0.25000
方案一(暴力法)
func myPow(x float64, n int) float64 {
if n < 0 {
n = -n
x = 1 / x
}
res := 1.0
for i := 0; i < n; i++ {
res = res * x
}
return res
}
- 超时
- 时间复杂度
- 空间复杂度
方案二(迭代)
func myPow(x float64, n int) float64 {
if n < 0 {
n = -n
x = 1 / x
}
ans := 1.0
current_product := x
for n != 0 {
if n % 2 == 1 {
ans = ans * current_product
}
n = n / 2
current_product = current_product * current_product
}
return ans
}
func myPow(x float64, n int) float64 {
if n == 0 {
return 1.0
}
if n < 0 {
n = -n
x = 1 / x
}
if n % 2 == 1 {
return x * myPow(x * x, n / 2)
}
return myPow(x * x, n / 2)
}
https://leetcode-cn.com/explore/featured/card/recursion-i/259/complexity-analysis/1227/