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;
        }
    }

 

上一篇:Java虚拟机-JVM各种参数配置大全详细


下一篇:寒假刷题记录2