Find dichotomy summary (a)

Title Description

Implement int sqrt(int x)functions.

Computes and returns x square root, wherein x is a non-negative integer.

Since the return type is an integer, the integer part of the result to retain only the fractional part is rounded down.

Example 1:

输入: 4
输出: 2

Example 2:

输入: 8
输出: 2
说明: 8 的平方根是 2.82842..., 
     由于返回类型是整数,小数部分将被舍去。

My Answer

class Solution {
    public int mySqrt(int x) {
        if(x==0){
            return 0;
        }
        if(x==1){
            return 1;
        }
        int left=0;
        int right=x;
        while(left<right){
            int middle=left+(right-left)/2;
            if(x/middle==middle){
                return middle;
            }else if(x/middle>middle){
                if(x/(middle+1)>middle+1){
                    left=middle;
                }else if(x/(middle+1)==middle+1){
                    return middle+1;
                }else if(x/(middle+1)<middle+1){
                    return middle;
                }
            }else{
                right=middle;
            }
        }
        return -1;
    }
}

to sum up

x/middle==middle

Originally used in the code is the middle * middle == x, but the question will arise, because the middle of the square may be greater than the maximum integer

Stones from other hills: the boundary value right people to x / 2, as the square root of x is less than or equal x / 2.

In addition, pay attention to the boundary value, if the code is less judgment of 0,1, the code is incomplete.

Released four original articles · won praise 1 · views 48

Guess you like

Origin blog.csdn.net/weixin_43638682/article/details/103983524
Recommended