题目
实现 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 = -nx = 1 / x}res := 1.0for i := 0; i < n; i++ {res = res * x}return res}
- 超时
- 时间复杂度
- 空间复杂度
方案二(迭代)
func myPow(x float64, n int) float64 {if n < 0 {n = -nx = 1 / x}ans := 1.0current_product := xfor n != 0 {if n % 2 == 1 {ans = ans * current_product}n = n / 2current_product = current_product * current_product}return ans}
func myPow(x float64, n int) float64 {if n == 0 {return 1.0}if n < 0 {n = -nx = 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/
