Easy DP solution with new edge cases- Java!


  • 0
    C
    public double myPow(double x, int n) {
           if(n == 0) return 1;
           if(n == -2147483648 && x < 0) return -x;
           if((n == 2147483647 || n == -2147483648) && x <= 1) return x;
           if((n == 2147483647 || n == -2147483648) && x > 1) return 0d;
          
           int absPower = Math.abs(n);     
           double dp[] = new double[absPower+1];
           dp[0] =1;
           dp[1] = x; 
           
           for(int i=2; i <= absPower ; i++){
                int tempPower = i/2;
                double squareVal = dp[tempPower] * dp[tempPower];
                dp[i] = (i%2 == 0)? squareVal: squareVal * dp[i%2];
           }
            return (n > 0) ? dp[absPower]: (1/dp[absPower]);
    
        }
    

Log in to reply
 

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