Math Number tricks
90. Pow(x, n)
You are given a number x and an integer n. Return x raised to the power n, written
xn.
For a positive n, xn is n copies of x multiplied together. x0 is 1. For a
negative n, xn is 1 divided by x−n, so 2−3 = 1/8.
The answer is a floating-point number, and different correct ways of computing it can round differently in the last digits. So an answer counts as right when it is within 10−6 of the expected answer, or, for an expected answer larger than 1 in absolute value, within 10−6 times that answer.
Example 1
Input: x = 1.5, n = 5
7.59375Explanation: 1.5 × 1.5 × 1.5 × 1.5 × 1.5 = 7.59375. Five copies of 1.5 are multiplied together.
Example 2
Input: x = -2, n = -3
-0.125Explanation: (−2)3 = −8, and a negative exponent turns the answer into 1 divided by that, so the answer is 1/(−8) = −0.125.
Example 3
Input: x = -1, n = 2147483647
-1Explanation: Multiplying −1 by itself flips the sign each time. The exponent is odd, so the answer is −1. This n
is the largest one allowed.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
-104 ≤ x ≤ 104-231 ≤ n ≤ 231 − 1- If
x = 0, thenn ≥ 1. - The exact value of xn lies between −104 and 104.
Clarifying questions
What you would ask an interviewer before writing any code.