LeetCode算法题-Easy-Math(69)
2019-02-14 本文已影响0人
Dane_404
69. Sqrt(x)
题目:Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
思路是:二分法查找平方根,如果中心的的平方大于X,说明平方根在左区间,则right = mid - 1,反之left = mid + 1。
class Solution {
public int mySqrt(int x) {
if (x == 0)
return 0;
int left = 1, right = x;
while (true) {
int mid = left + (right - left)/2;
if (mid > x/mid) { //不要用mid * mid > x,可能会溢出
right = mid - 1;
} else {
if (mid + 1 > x/(mid + 1))
return mid;
left = mid + 1;
}
}
}
}