Skip to content

Latest commit

 

History

History
35 lines (25 loc) · 673 Bytes

File metadata and controls

35 lines (25 loc) · 673 Bytes

Screen Shot 2022-01-16 at 01 41 21

// T.C. O(logn)
/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
var myPow = function(x, n) {
    if(n === 0) return 1;
    let pow = Math.abs(n);
    let res = pow % 2 === 0 ? myPow(x*x, pow / 2) : myPow(x*x, (pow - 1) / 2) * x;
    return n < 0 ? 1/res : res;
};

/*
x = 2, n = 10
10 % 2 === 0 => myPow(4, 5)

x = 4, n = 5
5 % 2 !== 0 => myPow(16, (5 - 1) / 2 * 4) => myPow(16, 8)

x = 16, n = 8
8 % 2 === 0 => myPow(256, 4)

x = 256, n = 4
4 % 2 === 0 => myPow()
*/