Implement pow(x, n).

public class Solution {
    public double myPow(double x, int n) {
// Need to take care of MIN_VAULE, cause -MIN > MAX
        if (n == Integer.MIN_VALUE) return x * myPow(x, n + 1);
        if (n < 0) return 1.0 / myPow(x, -n);
        if (n == 0) return 1.0;
        if (n == 1) return x;
        double temp = myPow(x, n / 2);
        if (n % 2 == 1) {
            return x * temp * temp;
        } else {
            return temp * temp;
        }
    }
}
Advertisements