题目描述:
Implement int sqrt(int x).Compute and return the square root of x.
题目要求:
要求我们求取x的平方根
题目分析:
本题与之前的Arranging Coins那道题很相似,都是可以使用一般的迭代方法O(n)的时间复杂度,和二分法O(logn)的时间复杂度http://blog.csdn.net/qq_27896185/article/details/53406632。
具体实现:
public class Solution {
public int mySqrt(int x) {
long start = 1;
long end = x;
//找到第一个比x小的位置,返回。
while (start + 1 < end) {
long mid = start + (end - start)/2;
if (mid * mid <= x) {
start = mid;
} else {
end = mid;
}
}
if (end * end <= x) {
return (int)end;
}
return (int)start;
}
}