My C++ code,easy to understand


  • 0
    X

    BinarySearch,and make sure mid is long,not int

     int mySqrt(int x) {
         if (x <= 1) 
             return x;
    
         int low = 1;
         int high = x / 2;
         while (low <= high) {
            long mid = (low + high) / 2;
            if (mid * mid == x)
                return (int)mid;
            else if (mid * mid > x)
                high = mid - 1;
            else
                low = mid + 1;
         }
    
         return low<high ? low : high;
    }

Log in to reply
 

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