iq.lab
Python starts when a code cell comes near or you run one
mediumRecursionBits and math target 25 min

Raise to a power

Write my_pow(x, n) that returns x raised to the power n. Here x is a float and n is an integer that can be positive, zero or negative. A negative power means one over the positive power: 5.0 to the power -2 is 1 / 25 = 0.04. Any nonzero x to the power 0 is 1.0.

Build the answer from multiplication and division. Do not use x ** n, pow or math.pow: the tests cannot stop you, but in an interview they skip the whole question.

Example 1
Inputx = 2.0, n = 10Output1024.0

Ten 2s multiplied together.

Example 2
Inputx = 2.0, n = -3Output0.125

One over the positive power: 1 / 23 = 1 / 8.

Example 3
Inputx = -2.0, n = 3Output-8.0

An odd power of a negative number stays negative.

Constraints
  • -100.0 < x < 100.0

  • -231 ≤ n ≤ 231 - 1

  • If x is 0, then n is positive.

  • The answer is between -104 and 104. Answers within 10-6 of the exact value are accepted.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.