C++ iterative / recursive solution


  • 0

    Iterative.

        double myPow(double x, int n) {
            if(x == 1) return x;
            if(x == -1) return n % 2 ? -1 : 1;
            if(x < 1 && n == INT_MAX || n == INT_MIN) return 0;
            double res=1;
            if(n < 0) x = 1/x, n = -n;
            while(n > 0){
                res = res * x;
                n--;
            }
            return res;
        }
    

    Recursive.

        double myPow(double x, int n) {
            if(x == 1) return 1;
            if(x == -1) return n % 2 ? -1 : 1;
            if(n == INT_MIN) return 0;
            if(n == 0) return 1;
            if(n < 0) return 1 / myPow(x, -n);
            if(n % 2) return x * myPow(x, n - 1);
            else{
                double d = myPow(x, n/2);
                return d * d;
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.