Title Link: Pow (x, N)
Implement POW (x, N).
The requirement for this problem is to implement the POW (x, n) function.
The n power of X is obtained. Direct violent thinking, multiply x by itself n times, time complexity O (n). When n is very large, the calculation time is too long.
Consider converting n to a binary number, i.e. n = a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n. The n power of x is X^n = x^ (a0*2^0 + a1*2^1 + a2*2^2 + ... + an*2^n) = x^ (a0*2^0) * x^ (a1*2^1) * x^ (a2*2^2) * ... * x^ (an*2^n).
For example, when n equals 11,
n=11: 1 0 1 1 (高位->低位)结果: x^4 x^2 x^1(连乘的结果)
So, divide n by 2 each time, multiply x by x, so that when a bit of binary is 1 o'clock, the x in this case is multiplied by the result.
Note that when n is negative, you need to divide the result by 1. At the same time, because a negative number is shifted right by 1, it is not divided by 2, so instead of dividing by 2, the shift is not used to increase speed.
Complexity of Time: O (LOGN)
Space complexity: O (1)
1 class Solution2 {3 Public:4 Double POW(Double x, int N)5 {6 Double Res = 1.0;7 for(int I = N; I != 0; I /= 2, x *= x)8 if(I & 1)9 Res *= x;Ten return N >= 0 ? Res : 1.0 / Res; One } A };
Reprint please indicate source: Leetcode---50. Pow (x, N)
Leetcode---50. Pow (x, N)