Java iterative solution, eliminates stack space in recursion


  • 0
    4
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        
        // negative case
        boolean extra = false;
        if (n < 0) {
            if (n == Integer.MIN_VALUE) {
                n = Integer.MAX_VALUE;
                extra = true;
            } else {
                n = -n;
            }
            
            x = 1 / x;
        }
        
        double temp = 1.0;
        if (extra) {
            temp *= x;
        }
        
        while (n != 1) {
            if (n % 2 != 0) {
                temp *= x;
            }
            
            x *= x;
            n /= 2;
        }
        
        return x * temp;
    }

Log in to reply
 

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