Implement the pow() Function
Filed under Microsoft
Free read 2 of 3Determine how to handle zero base with negative exponents and very large exponents.
The question
Implement the pow(x, n) function, which calculates x raised to the power n. The solution must handle positive and negative integer exponents efficiently.
Constraints
- -100.0 < x < 100.0
- -2^31 <= n <= 2^31-1
Examples
- Input
- x = 2.0, n = 10
- Output
- 1024.0
- Why
- 2 raised to the power of 10 is 1024.
- Input
- x = 2.0, n = -2
- Output
- 0.25
- Why
- 2 raised to the power of -2 is 1/4 = 0.25.
Approach
Determine how to handle zero base with negative exponents and very large exponents.
Multiply the base x by itself n times in a loop (O(N)).
Use binary exponentiation (exponentiation by squaring) to compute the result in O(log N) time.
Handle n = 0, n < 0, and x = 0.
Solution
O(log N) time, O(1) space
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
x = 1 / x
n = -n
res = 1.0
while n > 0:
if n % 2 == 1:
res *= x
x *= x
n //= 2
return res
Tips
- What they are testing: Test with n=0 to ensure it returns 1.0, and with n as the minimum integer to check for overflow.
- Common mistake: Using simple linear multiplication which leads to O(N) time, failing for large exponents.
Related Microsoft questions
Collected from public candidate posts and coding forums. Updated Nov 2026.