Formatted question description: https://leetcode.ca/all/50.html
50 Pow(x, n) Implement pow(x, n). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Note: -100.0 < x < 100.0 n is a 32-bit signed integer, within the range [−231, 231 − 1]
Use recursion to calculate in half, reduce n by half each time, so that n will eventually be reduced to 0, and any number to the power of 0 will be 1. At this time, multiply it back.
If n is even at this time, directly recurse the last time The obtained value can be returned as a square. If it is an odd number, it needs to be multiplied by the value of x.
Another thing to note is that n may be negative. For the case where n is negative, I can use its absolute value to calculate a result and then take its reciprocal. It was possible before, but now it’s added in the test case After a minus 2 to the 31st power, this will not work, because its absolute value exceeds the integer maximum value, there will be an overflow error, but you can use another way to write only one function, and handle n in each recursion. And then do the corresponding transformation.