Pow(x, n)

35 min · myPow()

Multiplying x by itself n times works for a small exponent. It falls apart when n is two billion.

Given a floating-point number x—a number that may contain a fractional part—and an integer n, return x raised to the power n. The exponent is the integer that controls how copies of the base are multiplied or turned into a reciprocal.

A few ground rules:

  • An exponent of 0 produces 1.
  • A negative exponent uses the reciprocal—one divided by the value: x^(-n) = 1 / x^n.
  • Inputs are chosen so the real result is finite and stays within the stated range.
  • Answers are compared with a tolerance—an allowed numerical gap—of 1e-5 to account for floating-point rounding.

Constraints

  • -100.0 <= x <= 100.0
  • -2^31 <= n <= 2^31 - 1
  • The true result lies within [-10^4, 10^4].

Hints

Halve the work

For an even exponent, compute x^(n/2) once and square it. An odd exponent needs one extra factor of x.

Read the exponent in bits

A binary digit is one 0 or 1 in an integer's base-two form. While halving the exponent, multiply the answer by the current base only when that digit is 1.

Treat INT_MIN carefully

INT_MIN is the smallest signed 32-bit integer, -2^31. Its magnitude is 2^31, which doesn't fit in a signed 32-bit integer. Move the exponent into a wider numeric type before negating it; don't use a 32-bit bitwise operation to take its absolute value.

Follow-up

Can you keep the logarithmic running time while using constant extra space?

Visible cases

Examples

Example 1

ready
Input
x = 2
n = 10
Expected
1024
Why
repeated squaring reaches 2^10 in four halvings

Example 2

ready
Input
x = 2.1
n = 3
Expected
9.261
Why
an odd exponent keeps one extra factor of 2.1

Example 3

ready
Input
x = 2
n = -2
Expected
0.25
Why
the negative exponent takes the reciprocal of 2^2

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite