Implement int
sqrt(int x)
.
Compute and return the square root of x.
这是一个关于二分法的题目。需要注意的是,乘法有可能会溢出,所以需要使用long定义mid这个变量。还有就是要注意返回的必须是high,而不能是low。
public class Solution {
public int sqrt(int x) {
long low=0, high=x;
while(low <= high) {
long mid = low+(high-low)/2;
long midd = mid*mid;
if(midd == x) {
return (int)mid;
}
else if(midd < x) {
low = mid+1;
}
else if(midd > x) {
high = mid-1;
}
}
return (int)high;
}
}