Java Solution (Taking Cara of Integer.MIN_VALUE)


  • 0

    I found this question added some new test cases which make it more reasonable.

    public class Solution {
        public double myPow(double x, int n) {
            if (n >= 0) {
                return helper(x, n);
            }
            if (n == Integer.MIN_VALUE) {
                if (x >= 0) {
                    return 1 / helper(x, Integer.MAX_VALUE);
                } else {
                    return -1 / helper(x, Integer.MAX_VALUE);
                }
            }
            return 1 / helper(x, -n);
        }
        
        private double helper(double x, int n) {
            if (n == 0) {
                return 1;
            }
            double result = helper(x, n / 2);
            result *= result;
            if (n % 2 == 1) {
                result *= x;
            }
            
            return result;
        }
    }
    

Log in to reply
 

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