Pow(x, n)
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
xto the powern; for a negativenthat is 1 / x⁻ⁿ. |n| goes up to 2³¹, so multiplying byxone time after another is too slow.- constraints
- −100 < x < 100
- −2³¹ ≤ n ≤ 2³¹ − 1
- x ≠ 0 or n > 0
- −10⁴ ≤ xⁿ ≤ 10⁴
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more divide and conquer problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.