题目分析
Implement int sqrt(int x).
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
这里采用二分法的方法来解这道题目。
代码
class Solution {
public int mySqrt(int x) {
if(x <= 0) return 0;
int low = 1, high = x;
while(low <= high) {
long mid = (high - low) / 2 + low;
if(mid * mid == x) {
return (int)mid;
} else if(mid * mid < x) {
low = (int)mid + 1;
} else {
high = (int)mid - 1;
}
}
return low - 1;
}
}
网友评论