这个题只想到二分法写,
private static int mysqrt(int x) { if(x<2) return x; /* 利用二分查找做,一般start = 2;end = x/2 + 1,因为end*end = (x^2/4+x+1) */ int start = 2; int end = x/2 + 1; int mid = (end - start) / 2 + start; while(start < end) { if(mid > x / mid) { end = mid; }else if(mid == x / mid) { return mid; }else { start = mid + 1; } mid = (end - start) / 2 + start; } return mid - 1;
另外看了他人实现的sqrt方法,感觉挺好的,下面附上博客地址:
https://blog.csdn.net/gqtcgq/article/details/48392255