Title Description:
Implement your own POW (double x, int n) method
Implementation ideas:
Consider bit operations. Consider the binary representation of N, take n=51 (110011) as an example, x^51 = x^1*x^2*x^16*x^32, so each time n is unsigned right one bit, and X takes the square of the current value, if n is shifted to the bottom
is 1, it will be res*x. Consider the special case, when N is Integer.min_value, at this time-n=integer.max_value+1, I was the first time I did not consider this boundary condition error ...
The method calculates the power of x by scanning 1 of different positions in the binary representation of n
Leetcode's AC code (Java version) is as follows:
Public classSolution { Public DoubleMypow (DoubleXintN) {if(N < 0){ if(n = = integer.min_value) {//consider boundary values return1/(MYPOW (x,integer.max_value) *x); }Else{ return1/mypow (x,-N); } } if(n = = 0){ return1.0; } Doubleres = 1.0; for(; n>0; x = x*x, n = n>>>1) {//while unsigned right shifts, X takes its own squared if((N & 1) > 0) {res*=x; } } returnRes; }}
Leetcode POW (x,n) implementation