leetcode——50. Pow(x, n)

真是不容易。。。

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if x==float(1):
            return 1
        if x==-float(1) :
            if n%2==1:return -1
            else:return 1
        if n>=2147483647 or n<=-2147483648:
            return 0
        if n<0:
            x=1/x
            n=-n
        if n==0:
            return 1
        elif n==1:
            return x
        res=1
        while n:
            if n%2==2:
                n//=2
                x*=x
            else:
                res*=x
                n-=1
        return res
执行用时 :356 ms, 在所有 python3 提交中击败了5.22%的用户
内存消耗 :13.6 MB, 在所有 python3 提交中击败了5.24%的用户
 
                                  ——2019.10.17
 

怎么当时就不会刷题呢,宁可自己做半天把它做出来也不看答案。
这不现在早就忘了?
public double myPow(double x, int n) {
        if(n<0) return 1.0/power(x,-n);
        else return power(x,n/2)*power(x,n/2)*power(x,n%2);
    }

    private double power(double x, int n) {
        if(n == 0) return 1;
        double v = power(x,n/2);
        if(n%2 == 0) return v*v;
        else return v*v*x;
    }

 

 ——2020.8.4

posted @ 2019-10-17 17:19  欣姐姐  阅读(174)  评论(0编辑  收藏  举报