Pow(x, n)

Pow(x, n) is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Bit Manipulation Patterns pattern, in the Bitwise Operations - Power of Two/Four Check subpattern.

Problem statement

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 0. - |x^n| <= 10^4. - The returned answer is accepted if its relative error is at most 1e-5.

Topics and companies

Topics: Math, Bit Manipulation, Divide and Conquer, Iteration.

How to practise Pow(x, n) on Thita.ai

Starter code is provided in C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(log |n|) time and O(1) space.

Open Pow(x, n) in the code editor, or read the Pow(x, n) editorial for a worked solution with its approach and complexity analysis.

Where Pow(x, n) sits in the DSA pattern sheet

Problems related to Pow(x, n)

Other problems that use the same Bitwise Operations - Power of Two/Four Check and Bit Manipulation Patterns techniques:

Preparing this workspace.