力扣Pow(x,n)

力扣:Pow(x,n)

用笨方法有一组数据过不去

就采用了 快速幂 + 递归
具体请看 :题解

C++

class Solution {
public:
    double calculate(double x, long long n) {
        if (n == 0) {
            return 1.0;
        }
        double y = calculate(x , n / 2);
        return n % 2 == 0 ? y * y : y * y * x;
    }
    double myPow(double x, int n) {
        long long N = n;
       return n > 0 ? calculate(x  , N) : 1.0 / calculate(x , -N);
    }
};

java

class Solution {
    public double calcu(double x, long  n) {
        if (n == 0) {
            return 1.0;
        }
        double y = calcu(x , n / 2);
        return  n % 2 == 0 ? y * y : y * y * x;
    }

    public double myPow(double x, int n) {
    long N = n;
    return n > 0 ? calcu(x , N) : 1.0 / calcu(x , -N);
    }
}

你可能感兴趣的:(leetcode,java,leetcode)