Recursive JavaScript solution


  • 0

    I came out with this implementation myself after a few submissions that covered edge cases.

    It's passing all cases but anyone able to improve my solution?

    /**
     * @param {number} x
     * @param {number} n
     * @return {number}
     */
    var myPow = function(x, n) {
        if (n === 0) return 1
        else if (n === 1) return x;
        else if (n === -1) return 1 / x;
        else if (n % 2 === 0) {
            const m = myPow(x, n/2);
            return m * m
        }
        else return x * myPow(x, n - 1);
    };
    

Log in to reply
 

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