LeetCode 69. Sqrt(x)
考点 | 难度 |
---|---|
Math | Easy |
题目
Given a non-negative integer x
, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5)
or x ** 0.5
.
思路
用binary search的方法,先设定left
是1,right
是x/2,再比较mid
和x/mid
,根据结果缩小范围。
答案
public int mySqrt(int x) {
if (x == 0)
return 0;
int left = 1, right = x/2;
while (true) {
int mid = left + (right - left)/2;
if (mid > x/mid) {
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
}