C++ AC implementation


  • 0

    To deal with INT_MIN overflow problem.

    We use

    1/x * myPow(1/x, -(n+1));    
    

    but not

     myPow(1/x, -n);
    

    Here is the AC code:

    class Solution {
    public:
        double myPow(double x, int n) {
            if(n<0) return 1/x * myPow(1/x, -(n+1));
            if(n==0) return 1;
            if(n==2) return x*x;
            if(n%2==0) return myPow( myPow(x, n/2), 2);
            else return x*myPow( myPow(x, n/2), 2);
        }
    };

Log in to reply
 

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