My O(log n) easy understand Java solution


  • 0
    T
    class Solution {
        public double myPow(double x, int n) {
            if (n==0) return 1;
            
            long longN=n;
            if (n<0) {
                longN=-longN;   //when n=Integer.MIN_VALUE, -n will be over the Integer.MAX_VALUE
                x=1/x;
            }
            
            double ans=1;       
            while (longN>0){
                if (longN%2==1) ans=ans*x; 
                longN=longN/2;
                x=x*x;
            }
            return ans;
        }
    }
    

Log in to reply
 

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