Runtime Error with no specific error


  • 0
    T

    My java code, last executed input is 0.000001, 2147483647. Runtime error. Anyone can help?

    public double pow(double x, int n) {
        double[] array1 = new double[Math.abs(n)];
        for (int i = 0; i<Math.abs(n); i++){
                if (i==0)
                array1[i] = x;
                else
                array1[i] =array1[i-1]*x; 
        }        
        if(n==0)
        return 1;
        if(n>0)
        return array1[array1.length-1];
        else
        return 1.0/array1[array1.length-1];
        
    }

  • 0
    S

    Your solution is impractical. It loops n times, uses O(n) memory, and can cause 'divide by 0' error when '1.0/array1[array1.length-1]' is executed and array1[array1.length-1] happens to be 0. When n is very large, it would become too much inefficient in terms of both space and time complexity. There is actually an O(logN) algorithm for this problem. Try to find it!


Log in to reply
 

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