my simple binary search solution


  • 0
    M
       public int mySqrt(int x) {
            
            if(x<=1) return x;
           
            long l=0, r=x, m=x/2;
            
            while(l<=r) {
                m=l+(r-l)/2;
                if (m*m<x){
                    l=m+1;
                }
                else if (m*m>x){
                    r=m-1;
                }
                else if(m*m==x){
                    return (int) m;
                }
            }

Log in to reply
 

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