Sqrt(x)

题目描述

Implement int sqrt(int x).
Compute and return the square root of x.

题目解答

解题思路

二分法,确定范围,然后逐步逼近
(1) x/mid = mid:return mid
(2) x/mid < mid:end = mid-1
(3) x/mid > mid:start = mid+1

当start = end = mid时:
(a) mid^2 < x,此时mid应为结果。下一步start = mid+1, end = mid,查找结束,此时应返回end
(b) mid^2 > x,此时mid-1应为结果。下一步start = mid, end = mid-1,查找结束,此时应返回end

代码实现

public class Solution {
    public int mySqrt(int x) {
        if(x < 0)
            return -1;
        if(x == 0 || x == 1)
            return x;
        int start = 0, end = x;
        while(start <= end) {
            int mid = (start + end) / 2;
            if(x/mid == mid)
                return mid;
            if(x/mid < mid) {
                end = mid -1;
            }else {
                start = mid + 1;
            }
        }
        return end;

    }
}

你可能感兴趣的:(二分法)