Simple Easy to Understand Binary Search Solution (C++)


  • 0
    H
    class Solution {
    public:
        int mySqrt(int x) {
            if ( x == 0 ) return 0;
            int res = 0, mid = 0;
            int L = 1, R = x;
            while ( true ){
                mid = (L + R)/2;
                res = x/mid;
                if ( mid == res ) return mid;
                if ( mid > res ) R = mid;
                if ( mid < res ) L = mid + 1;
                if ( L == R ) return --L;
            }
        }
    };
    

Log in to reply
 

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