public static double myPow(double x, int n) { if (x == 0){ return 0; } // Execute when n = -2147483648 // n = -n will cause an assignment error due to out of bounds // The solution is to first store n into the long variable l and then use l to operate long l = n; double res = 1; // If the exponent is negative, set x to the reciprocal and the exponent becomes positive for looping if(l < 0) { x = 1 / x; l = -l; } // When n is even: x^n = (x^2)^{n//2} // When n is odd: x^n = x(x^2)^{n//2} while(l != 0) { if((l & 1) == 1){ res *= x; } x *= x; l >>= 1; } return res; }
The idea in the while loop gives a picture for easy understanding