用二分查找,或者牛顿迭代
二分的话记得head设置成1而不是0,记得判断要用mid> x/ mid 而不要用mid * mid>x 因为乘法可能overflow max int
public class Solution {
public int sqrt(int x) {
if ( x <= 0)
return 0;
int head = 1;
int tail = x / 2;
while ( tail > head ){
int mid = ( head + tail )/2;
if ( mid <= x/mid && (mid+1) > x/(mid+1) )
return mid;
if ( mid < x/mid)
head = mid +1;
if ( mid > x/mid )
tail = mid -1;
}
return head;
}
}
牛顿法
public int sqrt(int x) {
if (x == 0) return 0;
double lastY = 0;
double y = 1;
while (y != lastY)
{
lastY = y;
y = (y + x / y) / 2;
}
return (int)(y);
}