Binary search result


  • 0

    In case of some extreme case x=2147395599, I use long long type.

    int mySqrt(int x) {
        if(x<=0) return 0;
        if(x==1) return 1;
        long long yl=0, yr=x, ym=(yl+yr)/2, dy=x;
        while(dy>1 && ym*ym !=x){
            if(ym*ym>x) yr=ym; else yl=ym;
            dy=yr-yl;
            ym=(yl+yr)/2;
        }
        return ym;
    }

Log in to reply
 

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