pow


  • 0
    S

    double myPow(double x, int n) {

     if(x==1.0 )
            return 1;
        
     if(x==-1.0)
            return n%2==0 ? 1 : -1;    
        
    if(n==INT_MIN || n==INT_MAX)
            return 0;
    if(n==0) return 1;
    if(n<0){
        n = -n;
        x = 1/x;
    }
    return n%2==0 ? myPow(x*x, n/2) : x*myPow(x*x, n/2);
    

    }


  • 0
    R

    Instead of calling it recursively, doing the same iteratively would save us memory.

    double myPow(double x, int n) {
            double a=1;
            int k=(n>0)?n:-n;
            while(k){
                if(k&1){
                    a=a*x;
                }
                k=k>>1;
                x=x*x;
            }
            if(n>0){
                return a;
            }
            else{
                return 1.0/a;
            }
            
        }
    
    

Log in to reply
 

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