[LeetCode Brush Questions] 69. The square root of x

Implementation  int sqrt(int x) function.

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

Since the return type is an integer, only the integer part of the result is retained, and the decimal part will be discarded.

Example 1:

Input: 4

Output: 2

Example 2:

Input: 8

Output: 2

Explanation: The square root of 8 is 2.82842..., since the return type is an integer, the fractional part will be truncated.

===========================================================================================================================================================================================================================================================================================================================================

analysis:

Method one: conventional solution

int mySqrt(int x){
    if(x==1)
    {
        return 1;
    }
    long i;
    for(i=1;i<=x/2;i++)
    {
        if(i*i>x)
        {
            break;
        }
    }
    return i-1;
}

 Method 2: Dichotomy

int mySqrt(int x){
    if(x == 1|| x == 0)
    {
        return x;
    }
    long left = 1;
    long right = x/2;
    while(left<=right)
    {
        long mid = (left + right)/2;
        if(mid*mid == x)
        {
            return mid;
        }
        else if(mid*mid < x)
        {
            left = mid+1;
        }
        else{
            right = mid-1;
        }
    }
    return left-1;

}

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

Guess you like

Origin blog.csdn.net/Zhouzi_heng/article/details/112385203