问题描述:
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;
}
};