Skip to content
Decoder

Pow(x, n)

Medium

Problem

Compute x raised to the power n, where x is a floating-point number and n is an integer that may be negative. Do not use the built-in power operator or Math.pow. Answers within 10^-5 are accepted.

Example 1

Input
x = 2.0, n = 10
Output
1024.0

Example 2

Input
x = 2.1, n = 3
Output
9.261

Example 3

Input
x = 2.0, n = -2
Output
0.25
Why
1 / 2^2

Constraints

  • -100.0 < x < 100.0
  • -2^31 <= n <= 2^31 - 1
  • Either x is not zero or n > 0.
  • -10^4 <= x^n <= 10^4

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.