Math Number tricks

90. Pow(x, n)

Medium 147 DSA Sheet

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

Output: 7.59375

Explanation: 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

Output: -0.125

Explanation: (−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

Output: -1

Explanation: 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.

x = -0.5, n = -2

Constraints

  • -104 ≤ x ≤ 104
  • -231 ≤ n ≤ 231 − 1
  • If x = 0, then n ≥ 1.
  • The exact value of xn lies between −104 and 104.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.