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;
    }
}

 

posted on 2016-10-08 14:04  Machelsky  阅读(124)  评论(0)    收藏  举报