Another accepted solution with comments. (Java)


  • 0
    J

    Another accepted solution. (Java)

    O(logn) runtime due to recursing on n/2 on each call of myPow().
    This also takes care of what happens when 0 is the base.

    class Solution {
        
        public double myPow(double base, int n) {
            
            // Anything raised to the 0th exponent will equal 1
            if (n == 0) return 1;
            
            // Anything with base 0 and non-zero exponent will equal 0
            if (base == 0) return 0;
            
            // Handle overflow error
            if (n == Integer.MIN_VALUE) {
                n += 1;
            }
            
            // If negative exponent, make n positive and adjust base
            if (n < 0) {
                
                n *= -1;
                base = 1/base;
                
                // If base is also negative, make it positive
                if (base < 0) {
                    base *= -1;
                }
            }
            
            return (n % 2 == 0) ? myPow(base * base, n / 2) : base * myPow(base * base, n / 2);
        }
    }
    

Log in to reply
 

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