Compute Power Function
Filed under Microsoft
Free read 3 of 3Check constraints on n, particularly handling integer overflow when n is -2^31.
The question
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
Constraints
- -100.0 < x < 100.0
- -2^31 <= n <= 2^31-1
- Function must handle negative exponents efficiently.
Examples
- Input
- x = 2.00000, n = 10
- Output
- 1024.00000
- Why
- 2^10 = 1024.
- Input
- x = 2.00000, n = -2
- Output
- 0.25000
- Why
- 2^-2 = 1 / (2^2) = 0.25.
Approach
Check constraints on n, particularly handling integer overflow when n is -2^31.
Multiply x by itself n times in a loop. O(N) time, failing for large n.
Use Binary Exponentiation (Exponentiation by Squaring). If n is negative, invert x and make n positive. If n is even, pow(x, n) = pow(x*x, n/2); if odd, x * pow(x, n-1).
n = 0 returns 1. Handle minimum integer value for n by casting or handling carefully to prevent overflow.
Tips
- What they are testing: Test edge cases like n = 0, n = -1, large positive and negative exponents, and base x = 0 or 1.
- Common mistake: Using a linear loop which leads to Time Limit Exceeded when n is very large.
Related Microsoft questions
Collected from public candidate posts and coding forums. Updated Nov 2026.