Implement int sqrt(int x).
二分法,找中值。注意不能用low<high来判断。举例:sqrt(5),low<high的话一直在2的右边搜索,最后low=3 high=3是不正确的,要再进入循环去得到最后的结果。
public class Solution { public int mySqrt(int x) { if(x<=1) { return x; } int low=0; int high=x; while(low<=high) { int mid=low+(high-low)/2; if(mid<x/mid) { low=mid+1; } else if(mid>x/mid) { high=mid-1; } else { return mid; } } return high; } }
浙公网安备 33010602011771号