Why TLE? in this c++ code which I have written


  • 0
    D
    double pow(double x, int n) {
            if(x==0) return 0;
            if(n==0) return 1;
            
            
            bool sign=true;
            if(n<0) {sign=false;n=-n;} 
            
            double res=1.0;
            while(n)
            {
                if(n&1) res=res*x;
                x=x*x;
                n=n>>1;
            }
            if(!sign)
            {
                res=(double)1.0/res;
                
            }
            return res;
            
        }

  • 0
    J

    Because your method is O(n). This question can be implemented in O(logn). x^n = x^(n/2) * x^(n/2) if n is even, and x^n = x * x^((n-1)/2) * x^((n-1)/2) if n is odd


Log in to reply
 

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