pow(x,n)

public class Solution{
	public double myPow(double x, int n) {
       boolean isNeg = false;

       if (n < 0) {
           x = 1 /x;
           isNeg = true;
        //int min value is -2147483648, max value is 2147483647, 
        // if n is min value, and convert it to positive, it will overflow,
        // now just make it one less and times it back in the end if n is negtive
           n = -(n+1);
       }

       double ans = 1, tmp = x;

       while(n != 0){
        if (n % 2 == 1) {
            ans *= tmp;
        }

        //first time 2 tmp times together, second round, 4 tmp times together, third round, 8 tmp times together,
        //it always is even number 2 power 
        //if n is odd, n will be 1 in the last and it will times the last one in the if statement abovess
        tmp *= tmp;
        n = n/2;

       }

       if (isNeg) {
           ans *= x;
       }

       return ans
    }
}

Last updated