- 首先贴上我的代码
public class Solution {
public int mySqrt(int x) {
if (x == 1 || x == 0) {
return x;
}
long start = 0;
long end = x / 2 + 1;
long mid = 0;
while (start <= end) {
mid = start + (end - start) / 2;
if (mid==x/mid || (mid <= x / mid && (mid + 1) > x / (mid + 1))) {
return (int)mid;
}
if (mid > x / mid) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}
- 同时再附上速度和内存占用都比较小的代码
public class Solution {
public int mySqrt(int x) {
long start = 0;
long end = x/2+1;
long mid = 0;
while(start<=end){
mid =(long) start+(end-start)/2;
if(mid*mid==x || (mid*mid<x && (mid+1)*(mid+1)>x)){
return (int)mid;
}
if(mid*mid>x){
end = mid-1;
}else{
start = mid+1;
}
}
return -1;
}
}