From : https://leetcode.com/problems/powx-n/
Implement
pow(x, n).
递归求解,空间复杂度为O(logn),时间复杂度为O(logn)
class Solution {
public:
double myPow(double x, int n) {
long long int num = n;
if(x==0.0) return 0;
if(x == 1) return 1;
if(x == -1) return (!(num&1))-(num&1);
if(num < 0) return myPowCore(1/x, -num);
return myPowCore(x, num);
}
double myPowCore(double x, long long int n) {
if(n == 0) return 1;
if(n == 1) return x;
return ((n&1)*x+(!(n&1)))*myPowCore(x*x, n>>1);
}
};
非递归方法,空间复杂度为O(1),时间复杂度为O(logn)
class Solution {
public:
double myPow(double x, int n) {
long long m = n;
if(x == 0) return 0;
else if(m == 0 || x == 1) return 1;
else if(m < 0) {
m = -m;
x = 1/x;
}
double ans = 1;
while(m) {
if(m&1) {
ans *= x;
}
m = m>>1;
x *= x;
}
return ans;
}
};