Tuesday, April 26, 2016

[LeetCode ] 50. Pow(x, n)

Implement pow(xn).
Subscribe to see which companies asked this question


public class Solution {
    public double myPow(double x, int n) {
        if(0 == n)
            return 1;
        if(0 == x)
            return 0;
        if(1 == x)
            return 1;
        if(1 == n)
            return x;
        
        if(n > 0)
            return myPow(x*x, n/2)*myPow(x, n%2);
        else{
            // Error: failed on negative number without this statement 
            return 1/(myPow(x*x, Math.abs(n)/2)*myPow(x, Math.abs(n)%2));
        }
    }
}

No comments:

Post a Comment