1.暴力法
效率较低
2.快速幂
需要考虑几种情况:
x=0
n=0
n为负数
快速幂的基本代码如下:
int pow3(int a,int b)
{
int ans = 1,base = a;
while(b!=0)
{
if(b&1)
ans *= base;
base *= base;
b>>=1;
}
return ans;
}
代码如下:
class Solution {
public:
double myPow(double x, int n) {
if (n == 0) return 1;
if(x==0) return 0;
long N = n;
if (n < 0) {
x = 1/x;
N = -N;
}
double res = 1;
//快速幂
while (N > 0) {
if ((N & 1) == 1) {
res = res * x;
}
x *= x;
N >>= 1;
}
return res;
}
};