50. Pow(x, n)

Implement pow(x, n).

public class Solution {
    public double myPow(double x, int n) {
        if(n < 0){
            return 1/ my_(x, -n);
        }else{
            return my_(x, n);
        }
    }

    private double my_(double x, int n){
        if(n == 0) return 1;
        double v = my_(x, n/2);
        if(n%2 == 0){
            return v*v;
        }else{
            return v*v*x;
        }
    }
}

if you check n%2 == 1 it will fail on some extreme case for example. x = 2.00000 & n = -2147483648

results matching ""

    No results matching ""