← Microsoft questions

Compute Power Function

Filed under Microsoft

Free read 3 of 3

Check 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

  1. Check constraints on n, particularly handling integer overflow when n is -2^31.

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.