10k

50. Pow(x, n)

Question

Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000

Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100

Example 3:

Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • n is an integer.
  • Either x is not zero or n > 0.
  • -104 <= xn <= 104

Algorithm

~~If you use a brute force way to solve it you will find many corner cases that even you cannot understand at first. Even code 1 can pass many test cases it will not be accepted by the system due to TLE.~~

Forget about the corner case, those chaos is due to the int overflow, if you change the exponent to a long number when doing calculations, everything should be find.

And also we can optimize the brute force way by using a divide and conquer. You divide the n to two parts and calculate them separately, and by using recursion this procedure will continue until to the based case where n = 1;

In this process, if n is odd, we just simply append an x to the result.

Code1

class Solution {
    public double myPow(double x, int n) {
        if (n == 0) return 1;
        double res = 1;
        boolean negative = false;
        if (n == Integer.MIN_VALUE) {
            return x == 1 ? 1.0000 : 0;
        } else if (n < 0) {
            n = -n;
            negative = true;
        }
        for (int i = 0; i < n; i++) {
            res *= x;
        }
        return negative ? 1.0 / res : res;
    }
}

Code2

class Solution {
    public double myPow(double x, int n) {
        return helper(x, (long) n);
    }
    
    private double helper(double x, long n) {
        if (n == 0) return 1;
        if (n < 0) return 1.0 / helper(x, -n);
        double res = helper(x, n / 2);
        if (n % 2 == 1) {
            return res * res * x;
        } else {
            return res * res;
        }
    }
}
Thoughts? Leave a comment