Implement
int sqrt(int x)
.
Compute and return the square root of x.
Solution 1: Pay attention to 0 and mid*mid may too big (>Integer.MAX_VALUE)
public class Solution {
public int mySqrt(int x) {
if (x<=0) return x;
int lo=1, hi=x;
while (lo<=hi) {
int mid=lo+(hi-lo)/2;
if (x/mid==mid) return mid;
else if (x/mid<mid) hi=mid-1;
else lo=mid+1;
}
return hi;
}
}
没有评论:
发表评论