Implement Pow (x, n).
This problem let us ask X of the N-square, if we simply use a for loop to X times their own n time, it would be too easy to think on the Leetcode, a word describing the pattern Tucson broken AH. OJ cannot pass because of timeout, so we need to optimize our algorithm so that it can work out the results more efficiently. We can use the recursive return binary calculation, each time the n is reduced by half, so that N will eventually shrink to 0, any number of 0 square is 1, this time we go back, if the n is even, directly the last recursive value to calculate a square return, if it is odd, you also need to multiply the value of the last X. Another thing that needs to be noticed is that N is likely to be negative, and for n is a negative number, we can first calculate a result with its absolute value and then take its reciprocal, the code is as follows:
Solution One
classSolution { Public: DoublePowDoubleXintN) {if(N <0)return 1/Power (x,-N); returnPower (x, N); } DoublePowerDoubleXintN) {if(n = =0)return 1; DoubleHalf = Power (x, N/2); if(n%2==0)returnHalf *half; returnX * Half *half; }};
There is also a way to use only one function, in each recursive check n positive and negative, and then do the corresponding transformation, the code is as follows:
Solution Two
classSolution { Public: DoublePowDoubleXintN) {if(n = =0)return 1; DoubleHalf = POW (x, N/2); if(n%2==0)returnHalf *half; Else if(N >0)returnHalf * Half *x; Else returnHalf * Half/x; }};
[Leetcode] Pow (x, n) x-th-square