LeetCode探索之旅(112)-50_pow

今天继续刷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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值