【LeetCode】Sqrt(x)

来源:互联网 发布:逃犯 熊孩子 知乎 编辑:程序博客网 时间:2024/06/06 20:50

Implement int sqrt(int x).

Compute and return the square root of x.

思路:

从[1,x/2]中利用二分法查找结果。

可取小不可取大(如8只能返回2,不能返回3),故在增加left的时候,要保存当前的中间值。

为了避免溢出,使用x/mid > mid,而不用x > mid*mid;

class Solution {public:    int sqrt(int x)     {        if(x < 2)return x;        int left = 1;        int right = x / 2;        int lastmid;        while(left <= right)        {            int mid = left + (right - left)/2;            if(x / mid > mid)            {                left = mid + 1;                lastmid = mid;            }            else if (x / mid < mid)            {                right = mid -1;            }            else return mid;        }        return lastmid;    }};


0 0
原创粉丝点击