-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
实现 pow 函数,输入 x、n,求解 x 的 n 次幂
思路
分治思想,拆解为子问题 -- x 的 n / 2 次幂相乘
function pwo(x, n) {
if (n < 0) {
return 1 / pwo(x, -n)
} else if (n === 0) {
return 1
} else {
let result = 1
const subResult = pwo(x, Math.floor(n / 2))
if (n % 2 === 1) {
// odd
result *= subResult * subResult * x
} else {
result *= subResult * subResult
}
return result
}
}Reactions are currently unavailable