Only 3 lines in Java (recursion)


  • 0
    G

    Only 3 lines in Java with fixed overflow:

    public double myPow(double x, int n) {
        if (n == 0) return 1;
        if (n < 0) return 1 / (x * myPow(x, ~n));
        return (n % 2 == 0) ? (myPow(x * x, n / 2)) : (x * myPow(x * x, n / 2));
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.