Skip to main content

Pow(x, n)

Medium
Data Structures and Algorithms
Editorial
Topics:
Math
Bit Manipulation
Divide and Conquer

Implement Solution.myPow, which receives a JSON number x and a 32-bit signed integer n. The value to compute is x raised to the integer power n, written mathematically as x^n.

For a positive n, multiply x by itself n times conceptually. For a negative n, the result is the reciprocal of x raised to -n. When n is zero, return 1, including when x is not 1.

Return the computed value as a floating-point number. The judge accepts answers whose relative error is at most 1e-5.

Example 1:

Input: x = 1.5, n = 4
Output: 5.0625
Explanation: Raising 1.5 to the fourth power gives 1.5 × 1.5 × 1.5 × 1.5 = 5.0625.

Example 2:

Input: x = 2, n = -3
Output: 0.125
Explanation: A negative exponent takes the reciprocal, so 2^-3 = 1 / 2^3 = 0.125.

Example 3:

Input: x = -7, n = 0
Output: 1
Explanation: Any non-zero base raised to the zero power is 1.

Constraints:

  • x is a JSON number.
  • -2^31 <= n <= 2^31 - 1.
  • x is non-zero or n > 0.
  • |x^n| <= 10^4.
  • The returned answer is accepted if its relative error is at most 1e-5.

Need help or want more practice?

Practise in an interviewGet AI Coach help