Implement pow(x, n): x raised to the integer power n (n may be negative).
Write n in binary. Square x at every step; whenever the current bit of n is 1, multiply that power of x into the result. x^13 = x^8 · x^4 · x^1.
1function myPow(x: number, n: number): number {2let e = Math.abs(n), res = 1;3while (e > 0) {4if (e & 1) res *= x;5x *= x;6e = Math.floor(e / 2);7}8return n < 0 ? 1 / res : res;9}
|n| = 13 = 1101₂.
Space: play/pause · ←/→: step