Binary search --- prescribing requirements

Prescribing requirements

69. Sqrt(x) (Easy)

Input: 4
Output: 2

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part 

Subject description:

  Given an integer, the integer find radicand.

Analysis of ideas:

  Sqrt prescribing a certain number x between 0 ~ x, and satisfies sqrt == x / sqrt. Binary search can be used to find sqrt between 0 ~ x.

  For x = 8, its evolution is 2.82842 ..., it should return the last 2 instead of 3. When the cycling conditions were l <= h and the loop exits, h l is always smaller than 1, that is h = 2, l = 3, so the return value of the last should not h l.

Code:

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

Guess you like

Origin www.cnblogs.com/yjxyy/p/11106128.html