leetcode69---Sqrt(x)(求x的平方根)

来源:互联网 发布:php开源投票系统 编辑:程序博客网 时间:2024/04/28 15:35

问题描述:

Implement int sqrt(int x).

Compute and return the square root of x.

问题求解:

二分法。O(logN)

class Solution {public:    int mySqrt(int x) {        long long  low =1;        long long  high=x;        long long  tmp;//用于和x比较        while(low < high)        {//二分法查找1~x里边的数,平方为tmp,与x比较            long long mid = low + (high-low)/2;            tmp = mid*mid;            if(tmp==x) return mid;            else if(tmp > x) high=mid-1;            else low=mid+1;        }        tmp = high*high;        if(tmp > x) return high-1;        else return high;    }};
0 0