4ms C++ solution ,with boundary judgement. I think it's important in an interview.


  • 0
    B
    const double DBL_MAX = 1.79769e+308;
    class Solution {
    public:
        double myPow(double x, int n) {
            if(n==0) return 1;
            bool isNeg=(x<0 && n%2!=0);
            if(n<0){
                if(x<1/DBL_MAX||x>-1/DBL_MAX){
                    x=1/x;
                }
                else{
                    return DBL_MAX;
                }
                if(n==INT_MIN){
                    x*=x;
                    n++;
                }
                n=abs(n);
            }
            x=abs(x);
            double ans=1;
            while(n>0){
                if(n&1){
                    if(ans<=DBL_MAX/x){
                        ans*=x;
                    }
                    else{
                        return isNeg?-DBL_MAX:DBL_MAX;
                    }
                }
                if(x>DBL_MAX/x){
                    return isNeg?-DBL_MAX:DBL_MAX;
                }
                x*=x;
                n>>=1;
            }
            return isNeg?-ans:ans;
        }
    };
    

    ========================Another recursive solution========================

    const double DBL_MAX = 1.79769e+308;
    class Solution {
    public:
        double myPow(double x, int n) {
            if(n==0) return 1;
            if(n==1) return x;
            double ans=1;
            if(n<0){
                if(x>=1/DBL_MAX || x<=-1/DBL_MAX){
                    x=1/x;
                }
                else{
                    return DBL_MAX;
                }
                if(n==INT_MIN){
                    ans*=x;
                    n++;
                }
                n=abs(n);
            }
            bool isNeg=(x<0 && n%2!=0);
            x=abs(x);
            double half=myPow(x,n/2);
            if(n%2==0){
                if(half<=DBL_MAX/half){
                    half*=half;
                }
                else{
                    return DBL_MAX;
                }
            }
            else{
                if(half<=DBL_MAX/half){
                    half*=half;
                    if(half<=DBL_MAX/x){
                        half*=x;
                    }
                    else{
                        return DBL_MAX;
                    }
                }
                else{
                    return DBL_MAX;
                }
            }
            if(isNeg) ans*=-1;
            if(half<=DBL_MAX/abs(ans)){
                ans*=half;
            }
            return ans;
        }
    };

Log in to reply
 

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