LeetCode---(69)Sqrt(x)

来源:互联网 发布:四维数据的图形表示 编辑:程序博客网 时间:2024/05/22 01:46

Implement int sqrt(int x).

Compute and return the square root of x.

利用二分法查找:第一种可能性是直接找到能够麻烦要求的数;第二种可能性是找到相邻的两个数,可以比较两个数哪一个离target更近,不过题目当中希望找的是更小的那个数。

class Solution {public:    int mySqrt(int x) {        if(x<=1)            return x;        int left=1;        int right=x;        unsigned long long temp=0;        while(left<=right)        {            int mid=(left+right)/2;            if(mid==x/mid)                return mid;            else if(mid<x/mid)                left=mid+1;            else                right=mid-1;                    }        return right;    }};


0 0