[Leetcode] One question per day (69 x square root)

Insert picture description here
Ideas:
1. The arithmetic square root of a non-negative integer must be between 0 and itself, so you can use the dichotomy to find in the interval
2. Arithmetic square roots greater than or equal to 2 only keep the integer part less than or equal to half of the input value
3. Constantly search and compare the square of the intermediate value and the input value to find the arithmetic square root that retains the integer part, that is, (x/mid<mid)
code implementation:

int mySqrt(int x){
    
    
    int low=0;
    int high=x;
    int mid;

    if(x<=1)
    {
    
    
        return x;
    }

    while(low+1<high)
    {
    
    
        mid=low+(high-low)/2;
        if(x/mid<mid)
        {
    
    
            high=mid;
        }
        else
        {
    
    
            low=mid;
        }

        }
        return low;
    }

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

Guess you like

Origin blog.csdn.net/qq_45657288/article/details/106028544