什么是幂函数(什么是幂函数)

2021-09-27:Pow(x, n)。实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,x**n)。力扣50。

福大大 答案2021-09-27:

遍历n的二进制位。

时间复杂度:O(logn)。

空间复杂度:O(1)。

代码用golang编写。代码如下:

package mainimport ( "fmt" "math")func main() { x := 5.3 n := 10 ret := myPow(x, n) fmt.Println(ret)}func pow(a int, n int) int { ans := 1 t := a for n != 0 { if (n & 1) != 0 { ans *= t } t *= t n >>= 1 } return ans}// x的n次方,n可能是负数func myPow(x float64, n int) float64 { if n == 0 { return 1 } pow := n + 1 if n != math.MinInt64 { pow = n } t := x ans := 1.0 for pow != 0 { if (pow & 1) != 0 { ans *= t } pow >>= 1 t = t * t } if n == math.MinInt64 { ans *= x } if n < 0 { return 1.0 / ans } else { return ans }}

执行结果如下:



***

[左神java代码](https://github.com/algorithmzuo/coding-for-great-offer/blob/main/src/class29/Problem_0050_PowXN.java)