Interesting Java Solution with some tricks that beats 95%


  • 5

    Here is my recursive solution to this problem. Note that one trick when dealing with negative max Integer is to instead of -n where overflow happens have it -(n+1) then multiply it by x.

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

  • 0
    W

    @mehranangelo nice trick to avoid overflow.


Log in to reply
 

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