Explore all possible recursive solution, Java


  • 0
    E
    public class Solution {
    	public double myPow(double x, int n) {
    		if (n == 0)
    			return 1;
    		if (n < 0) {
    			n = -n;
    			x = 1 / x;
    		}
    		if (n % 3 == 0) {
    			return myPow(x * x * x, n / 3);
    		} else if (n % 3 == 1) {
    			return x * myPow(x * x * x, n / 3);
    		} else {
    			return x * x * myPow(x * x * x, n / 3);
    		}
    	}
    
    	public double myPow(double x, int n) {
    		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);
    	}
    /*
    	public double myPow(double x, int n) { // StackOverflowError:
    		return x * myPow(x, n - 1);
    	}
    */
    }

Log in to reply
 

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