69. Sqrt(x)

69. Sqrt(x)

题目

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 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 will be trunca

解析

class Solution_69 {
public:
    int mySqrt(int x) {

        int ret = 0;
        int mx = INT_MAX;
        while (1)
        {
            long long temp = ret*ret;
            long long temp1 = (long long)(ret+1)*(long long)(ret+1); //关于数据的题考虑越界和边界条件;*操作之前强制类型转换
            if (temp1>mx)
            {
                return ret;
            }
            if (temp<= x && temp1>x) //考虑越界的问题
            {
                break;
            }
            ret++;
        }
        return ret;
    }

    int sqrt(int x) //牛顿逼近法
    {
        long r = x; 
        while (r*r > x)
            r = (r + x / r) / 2; 
        return r;
    }


    //特比特别要注意两点:第一right要取x / 2 + 1  这个还不是最重要的,其实只是影响速度
    //第二:要用x / middle > middle  来表示x > middle*middle  不然会溢出
    //第三:判断相等时用x / middle >= middle && x / (middle + 1) < (middle + 1)
    int sqrt_(int x)
    {
        if (x<2)
        {
            return x;
        }
        int l = 1, r = x/2+1;
        int mid=0;
        while (l<=r)
        {
            //mid = l + (r - l) / 2; 
            mid = l + ((r - l) >> 1); //位运算的优先级低于算术运算 bug: mid=l+(r-l)>>1
            if (mid != 0)
            {
                if (x / (mid + 1)<mid + 1 && x / mid>=mid)
                {
                    return mid;
                }else if (x / mid>=mid) //不使用x>mid*mid
                {
                    l = mid + 1;
                }
                else if(x / mid< mid)
                {
                    r = mid - 1;
                }
            }
            
        }

        return mid;
    }

    int sqrt_ref(int x) {
        if (x == 0){
            return 0;
        }
        if (x < 0){
            return -1;
        }
        int left = 1, right = x / 2 + 1, middle;
        while (left <= right){
            middle = (left + right) / 2;
            if (x / middle >= middle && x / (middle + 1)<(middle + 1)){
                return middle;
            }
            else if (x / middle>middle){
                left = middle + 1;
            }
            else{
                right = middle - 1;
            }
        }
        return right;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8651006.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞