50. Pow(x, n)
es6
function Pow(x,n){
return x**n;
}
//注意floor
var myPow = function(x, n) {
if(n<0){
x = 1/x
n = -n
}
let ans = 1;
while(n>0) {
if((n %2) == 1) {
ans = ans * x;
}
x = x*x
n = Math.floor(n/2)
// console.log(n)
}
return ans
// console.log(n)
};
1.暴力法
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
let N = n
if(N < 0) {
x = 1/x;
N = -N
}
let ans = 1;
for(let i = 0; i< N; i++)
ans = ans * x;
return ans;
};
1.00000
2147483647
当n十分大时,会超时
2.递归快速幂
class Solution {
public:
double fastPow(double x, long long n) {
if (n == 0) {
return 1.0;
}
double half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half
} else {
return half * half * x;
}
}
//主函数
double myPow(double x, int n) {
long long N = n;
if (N < 0) {
x = 1 / x; //对 根号x = 1/x
N = -N;
}
return fastPow(x, N);
}
};
//迭代法
class Solution {
public:
double myPow(double x, int n) {
long long N = n;
if (N < 0) {
x = 1 / x;
N = -N;
}
double ans = 1;
double current_product = x;
for (long long i = N; i >0; i /= 2) {
//结束条件??
if ((i % 2) == 1) {
ans = ans * current_product;
}
current_product = current_product * current_product;
}
return ans;
}
};










网友评论