今天继续刷LeetCode,第50题,求浮点数的n次方
分析:
n为三种情况(正数,0,负数)
1、正数的时候,循环累计叠成。(改进方法是采用二分累乘)
2、负数的时候,可以对浮点数去导数后,按照正数的计算方法计算;
3、为0的时候,返回为0
问题:
1、n可能为很大的数,需要优化,减少计算次数;
2、注意整型越界的情况
附上C++代码:
class Solution {
public:
double myPow(double x, long long n) {
double res=1.0;
if(n<0)
{
n=-1*n;
x=1/x;
}
while(n)
{
if(n&1)
res*=x;
x=x*x;
n>>=1;
}
return res;
}
};
附上Python代码1:
class Solution:
def myPow(self, x: float, n: int) -> float:
if n>0:
flag=1
else:
flag=-1
n=flag*n
def p(x,n):
if n==0:
return 1
if n==1:
return x
if n%2==0:
return p(x*x,n//2)
else:
return x*p(x*x,n//2)
res=p(x,n)
if flag==-1:
res=1/res
return res
附上Python代码2:
class Solution:
def myPow(self, x: float, n: int) -> float:
res=1
if n>0:
flag=1
else:
flag=-1
n=flag*n
while n:
if n&1:
res*=x
x=x*x
n>>=1
if flag==-1:
res=1/res
return res