Java O(logn) handling Integer.MIN_VALUE elegantly


  • 0

    I know some posts handle MIN and divide it to many cases such as x>0 or x<0. I find this way is simpler. You write the mathematically equivalent equation and simply let the recursion do the rest of the job.

    public class Solution {
        public double myPow(double x, int n) {
            //when n==MIN, -n is still MIN, so we convert MIN to MAX manually and 
            //because |MIN|=|MAX|+1, additional 1/x is needed 
            if (n == Integer.MIN_VALUE) {
                return myPow(1 / x, Integer.MAX_VALUE) * 1 / x;
            }
            if (n < 0) {
                x = 1 / x;
                n = -n;
            }
            if (n == 0) {
                return 1;
            }
        
            return n % 2 == 0 ? myPow(x * x, n / 2) : 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.