实现 pow(x, n) ,即计算 x 的整数 n 次幂函数(即,x ** n )。

思路

  1. x ** (a + b) = (x ** a) * (x ** b)
  2. x ** (a * b) = (x ** a) ** b
  3. x ** (2k + i) = (x ** i) * (x ** 2k) = (x ** i) * ((x ** 2) ** k)
1
2
3
4
5
6
7
8
9
10
11
12
var myPow = function (x, n) {
const isNegative = n < 0
n = Math.abs(n)
const factors = []
while (n > 0) {
factors.push(n % 2 === 1 ? x : 1)
n = Math.floor(n / 2)
x = x * x
}
const product = factors.reduce((result, cur) => result * cur, 1)
return isNegative ? 1 / product : product
}