Pow(x, n)

Medium#50half the power

You get a number x and a whole number n, which may be negative. Work out x to the power n without a ready-made power function. Our example: x = 2, n = -13 — the answer is 1 / 8192 = 0.0001220703125.

input
x: a number, the base. n: an integer, the power; it may be negative.
returns
x to the power n; for a negative n that is 1 / x⁻ⁿ. |n| goes up to 2³¹, so multiplying by x one time after another is too slow.
constraints
  • −100 < x < 100
  • −2³¹ ≤ n ≤ 2³¹ − 1
  • x ≠ 0 or n > 0
  • −10⁴ ≤ xⁿ ≤ 10⁴
our 20 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} x
 * @param {number} n
 * @return {number}
 */
function myPow(x, n) {

}
Ctrl ↵
format
reset

saved in this browser

20 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more divide and conquer problems

Pattern “Divide and conquer” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.