My java solution


  • 0
    L
    public double myPow(double x, int n) {
        if(n==0) return 1;
        else if(n<0) return 1/unsignedPow(x, -n);
        else return unsignedPow(x, n);
    }
    
    public double unsignedPow(double x, int n){
    	if(n==1) return x;
    	if(n%2==1) return x*myPow(x,n-1);
    	else
    	{
    		double tmp = myPow(x, n/2);
    		return tmp*tmp;
    	}
    }

  • 0
    A

    my code is as follows:

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

    the test case is
    1.00000
    -2147483648
    why the result is java.lang.StackOverflowError, but your code is accepted?


  • 0
    S

    Because -n in your code will cause overflow, while in his code it's just considered 0.


Log in to reply
 

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