AC代码:
public int sqrt(int x) { // write your code here if(x<0) throw new IllegalArgumentException(); else if(x<=1){ return x; } int start = 1; int end = x; while(start+1<end){ int mid = start + (end - start)/2; if(mid == x/mid){ return mid; } else if(mid > x/mid){ end = mid; } else{ start = mid; } } if(end>x/end){ return start; } return end; }
代码解释:
思想:使用二分查找法
方法: n == x / n 这比② n*n == x 好一点,因为②中n*n可能造成数据超出 int 范围
详细解释:
int mid = start + (end - start)/2; 使得每次mid都是中间数或者是比中间数大一的数
mid > x/mid 说明查找的区间在start到mid之间
最后一个if十分重要
因为当mid十分接近,甚至是等于需要的数时;执行x/mid得到的数却是比mid大一点的数时,此时应该结束循环,但是程序会判断执行else{start = mid};
然后因为start+1>end不成立而结束循环,但是没有返回值,此时如果没有if语句,程序结束返回end,却不是正确答案,正确答案应该是start;
所以用if语句判断得到正确返回值start;
不理解的看x = 4187案例:
正确结果是 64
原文:https://www.cnblogs.com/S-Evildoer/p/11314449.html