leetcode 69.x square root (Java binary search easy)

https://leetcode-cn.com/problems/sqrtx/

Achieve int sqrt (int x) function, a given number, seeking sqrt (x) and the integer part retained.

 

Binary search, so that l = 1, h = x, is determined l <= h, when out of the loop, i.e., sqrt (x) is not an integer, return h, because l when out of the loop> h, this question requires leaving only the integer portion , not rounded.

class Solution {
    public int mySqrt(int x) {
        if(x<=1) return x;
        int l=1,h=x;
        while(l<=h){
            int mid=l+(h-l)/2;
            int sqrt=x/mid;
            if(sqrt==mid){
                return mid;
            }
            else if(sqrt<mid){
                h=mid-1;
            }
            else{
                l=mid+1;
            }
        }
        return h;
    }
}

 

Guess you like

Origin www.cnblogs.com/y1040511302/p/11569004.html