Practice/Meta/Leetcode 50. Pow(x, n)
CodingMust
Implement a function that calculates x raised to the power of n, where x is a floating-point number and n is a signed 32-bit integer. Your solution must handle both positive and negative exponents efficiently.
The naive approach of multiplying x by itself n times would take O(n) time, which is too slow for large values of n. You need to implement an algorithm that runs in O(log |n|) time.
Example 1:
Input: x = 2.0, n = 5 Output: 32.0 Explanation: 2 * 2 * 2 * 2 * 2 = 32
Example 2:
Input: x = 3.0, n = -2 Output: 0.11111 Explanation: 3^(-2) = 1/(3^2) = 1/9 ≈ 0.11111
Example 3:
Input: x = 2.0, n = -2147483648 Output: 0.0 Explanation: The result is so small it's effectively zero
Example 4:
Input: x = 1.0, n = 123456789 Output: 1.0 Explanation: 1 raised to any power is 1