Easy to Understand solution with Code


  • 1
    R
    public class Solution {
        
        public double myPow(double base, int power) {
            if(power > 0){
                return calculatePower(base,power);
            }else if(power < 0){
                return 1/calculatePower(base, -power);
            }else{
                return 1;
            }
        }
        
        public double calculatePower(double base, int power){
            if(power == 0){
                return 1;
            }else if(power == 1){
                return base;
            }
    
            double inter = calculatePower(base,power/2);
    
            if(power%2 == 0){
                return inter*inter;
            }else{
                return inter*inter*base;
            }
        }
    }
    

Log in to reply
 

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