LeetCode 50. Pow(x, n)

I got stuck on this problem, even after looking at answers, I could not follow algorithm. Following video really helped me understand it:

Here is my solution after watching this video:

/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
    if (x == 0) return 0

    if (n == 0) return 1

    if (n < 0) {
        x = 1/x
        n = -1 * n
    }

    const half = myPow(x, Math.floor(n/2))
    let ans = half * half

    if (n%2 == 1) ans = x * ans

    return ans
};

Published on