Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.
int mySqrt(int x) {
    if(x==0||x==1)
        return x;
    int left=1,right=x/2;
    while(left<=right)
    {
        int mid=left+(right-left)/2;
        if(mid==x/mid)
            return mid;
        if(mid<x/mid)
            left=mid+1;
        else
            right=mid-1;
    }
    return left-1;
}

 

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐