Java教程

50. Pow(x, n)

本文主要是介绍50. Pow(x, n),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

This problem is very easy to solve if using bruteforece solution, the time complexity is O(n).

    public double myPow(double x, int n) {
        if (n == 0)
            return 1;
        double res = 1;
        int m = Math.abs(n);
        for (int i = 0; i < m; i++) {
            res *= x;
        }

        if (n > 0)
            return res;
        else
            return 1 / res;
    }

But this will caused a TLE, so we need to think about a O(logn) solution:

1. When the m is an even number, we make x = x*x, m = m/2;

2. When the m is an odd number, we need to multiple an extra x with res.

3. The m is odd number will must happen if m!=0, because m must be 1 at last.

    public double myPow_Iteration(double x, int n) {
        double res = 1;
        int m = n;
        while (m != 0) {
            if (m % 2 != 0)
                res *= x;
            x *= x;
            m /= 2;
        }
        if (n >= 0)
            return res;
        else
            return 1 / res;
    }

The Recursive solution with the same time complexity with Iteration solution is:

    public double myPow(double x, int n) {
        double res = helper(x, n);
        if (n < 0)
            return 1 / res;
        else
            return res;
    }


    private double helper(double x, int n) {
        if (n == 0)
            return 1;
        if (n % 2 == 0) {
            return helper(x * x, n / 2);
        } else {
            return x * helper(x * x, n / 2);  //when n==1, this line will be executed, and return x*1;
        }
    }

 

这篇关于50. Pow(x, n)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!