leetcode50. Pow(x, n)

313 阅读1分钟

实现 pow(x, n) ,即计算 x 的 n 次幂函数。

题目链接:leetcode-cn.com/problems/po…

思路一:暴力法求解,将x乘以n次(时间复杂度过高)

    /*
    蛮力法:时间复杂度O(n)
     */
    public static double myPow(double x, int n) {
        if (n == 0 || x==1)
            return 1;
        double temp = x;
        for (int i = 1; i < Math.abs(n); i++) {
            x *= temp;
        }
        return n > 0 ? x : 1 / x;
    }

思路二:快速幂算法求解 初次接触快速幂算法,在计算大指数问题时,快速幂能有效的减少运算次数!
例子:2^13 = 2^8 * 2^4 *2^1
快速幂知识点链接 oi-wiki.org/math/quick-…
快速幂算法循环实现

    public double myPow2(double x, int n) {
        if (n == 0 || x == 1)
            return 1;
        double res = 1.0;
        for(int i = n; i != 0;i /= 2){
            if((i&1)==1)//为奇数时
                res *= x ;//将结果记录
            x *= x;//翻倍:例如2^4 = (2^2)^2
        }
        return n>0?res:1/res;
    }

快速幂算法递归实现

    /*
    快速幂算法递归实现
     */
    public static double myPow3(double x, int n) {
        long N = n;
        if (N < 0) {
            N = -N;
            x = 1 / x;
        }
        return fastPow(x, N);
    }

    public static double fastPow(double x, long n) {
        if (n == 0)
            return 1.0;
        double res = fastPow(x, n / 2);
        if (n % 2 == 1)//为奇数时
            return res * res * x;
        else
            return res * res;
    }

思路三:二分幂算法 二分幂算法理解起来较为容易。 当为奇数时:2^13 = 2^6 * 2^6 * 2^1 当为偶数时:2^12 = 2^6 * 2^6

    /*
    二分幂算法
     */
    public static double myPow4(double x, int n) {
        int N = n;
        if (N < 0) {
            N = -N;
            x = 1 / x;
        }
        return BinaryPow(x, N);
    }

    public static double BinaryPow(double x, int n) {
        if (n == 0)
            return 1;
        if (n == 1)
            return x;
        double res = BinaryPow(x, n / 2);
        res *= res;
        if ((n & 1) == 1)
            res *= x;
        return res;
    }