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;
}
}