难度:中等
题目描述:
实现函数double Power(double base, int exponent),求base的exponent次方。不得使用库函数,同时不需要考虑大数问题。
示例:
输入: 2.00000, 10输出: 1024.00000
解题思路:
位运算
var myPow = function(x, n) {if (n === 0) {return 1;}if (n === 1) {return x;}const isNegative = n < 0; // 是否是负指数let absn = Math.abs(n);let result = 1;while (absn) {// 如果n最右位是1,将当前x累乘到resultif (absn & 1) {result = result * x;}x = x * x; // x自乘法absn = Math.floor(absn / 2); // n右移1位}return isNegative ? 1 / result : result;};
二分法
var myPow = function(x, n) {const isNegative = n < 0; // 是否是负指数const result = absMyPow(x, Math.abs(n));return isNegative ? 1 / result : result;};function absMyPow(base, exponent) {if (exponent === 0) {return 1;}if (exponent === 1) {return base;}const subResult = absMyPow(base, Math.floor(exponent / 2));return exponent % 2 ? subResult * subResult * base : subResult * subResult;}
