Accepted short Java recursive solution. With comments.


  • 0
    P
    public double pow(double x, int n) {
    	
    	// Handle edge cases like 1^-Integer.MIN_VALUE or  x^0
    	if (n==0) return 1;
    	if (x==1) return 1;
    	if (x==-1) return (n!=Integer.MIN_VALUE && (n<0 && (-n)%2==1)||(n>0 && n%2==1)) ? -1 : 1;
    	if (n<0) return 1/pow(x,-n);
    	
    	// Power x for i=2,4,8,16,32......
    	double X = x;
    	long i = 2;
    	for (; i<=n; i*=2) X *= X;
    	i /= 2;
    	
    	// Multiple recursively for next power (n-1) if (i < n)
    	return n > i ? X * pow(x, (int)(n-i)) : X;
    }

  • 0
    W

    It will throw stackoverflow error if (n == Integer.MIN_VALUE && x != 1 && x != -1)


Log in to reply
 

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