Pow(x, n)
Calculate x raised to the power n in logarithmic time using binary exponentiation and integer overflow protection.
01The problem
Implement pow(x, n), which calculates x raised to the power n (i.e., x^n).
| Input | Output | Why |
|---|---|---|
x = 2.00000, n = 10 | 1024.00000 | 2^10 = 1024 |
x = 2.10000, n = 3 | 9.26100 | 2.1^3 = 9.261 |
x = 2.00000, n = -2 | 0.25000 | 2^(-2) = 1 / (2^2) = 1 / 4 = 0.25 |
Constraints: -100.0 < x < 100.0, -2^31 <= n <= 2^31 - 1, n is an integer. Either x is not zero or n > 0. Output is within [-10^4, 10^4].
Loading the rest of the lesson…