Implement pow(x, n).
计算x的n次方。计算很容易,但是为了加快时间,n可以除以2,这样就可以自己乘以自己
比如4的4次方我就直接先计算4乘以4,然后再16乘以16即可
class Solution {//C++代码可以运行通过
public:
double pow(double x, int n) {
if(n == 0){
return 1;
}
else if(n < 0){
x = 1 / x;
n = -1 * n;
}
double result = 1;
while(n > 0){
if(n % 2 == 1){
result *= x;
}
n /= 2;
x *= x;
}
return result;
}
};
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def pow(self, x, n):#Python偷懒代码
return x**n
class Solution:
# @param x, a float
# @param n, a integer
# @return a float
def pow(self, x, n):
if n==0:
return 1
if n<0:
x=1/x
n=-n
result=1
while (n>0):#注意收敛条件,不断把n除以2
if (n%2==1):
result=x*result#遇到是奇数,就把当前值乘以累计乘积
x=x*x
n=n//2
return result