CodeSpeek

Pow(x, n)

Medium · Math & Geometry

You are given a floating point base value and an integer exponent. Compute the base raised to that exponent power without using a built-in power operator. The exponent can be negative, which means the result is the reciprocal of the base raised to the absolute value of the exponent, and it can be zero, in which case the result is 1.

Examples

Input:  x = 2.0, n = 10
Output: 1024.0
Why:    2 multiplied by itself 10 times equals 1024.
Input:  x = 2.1, n = 3
Output: 9.261
Why:    2.1 * 2.1 * 2.1 equals 9.261.
Input:  x = 2.0, n = -2
Output: 0.25
Why:    A negative exponent means take the reciprocal: 1 / (2^2) = 0.25.

Constraints

-100.0 < x < 100.0, -2^31 <= n <= 2^31 - 1, x is not 0 when n is negative, the result is guaranteed to be within the range of a double

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Pow(x, n)

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Pow(x, n). Reference solutions from the NeetCode repository (MIT) are used to verify our tests.