How to deal with this test case pow(1.000001, Integer.MAX_VALUE) ?


  • 0
    B

    If x = 1.000001 and n = Integer.MAX_VALUE, how to deal with this case? how to do detect double overflow in java?


  • 0
    Z

    Look at the break inside the loop.

    public class Solution {
        public double pow(double x, int n) {
            if(n > 0)
                return forPositiveExponent(x, n);
    
            if(n == 0)
                return 1;
    
            return forNegativeExponent(x, n);
        }
    
        private double forNegativeExponent(double x, int n) {
            return 1d / forPositiveExponent(x, -n);
        }
    
        private double forPositiveExponent(double x, int n) {
            double positiveX = x < 0 ? -x : x;
    
            double result = positiveX;
    
            int i = 1;
            int sign = x < 0 ? (n % 2 == 1 ? -1 : 1) : 1;
            while (i < n && Double.MIN_VALUE <= result && result <= Double.MAX_VALUE) {
                double prev = result;
                result *= positiveX;
                if(prev == result)
                    break;
    
                ++i;
            }
    
            return sign * result;
        }
    }

Log in to reply
 

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