[LeetCode]--69. Sqrt(x)

来源:互联网 发布:怎么注册淘宝小号 编辑:程序博客网 时间:2024/06/05 04:39

Implement int sqrt(int x).

Compute and return the square root of x.

我采用的是二分法。每次折中求平方,如果大了就把中值赋给大的,如果小了就把中值赋给小的。

public int mySqrt(int x) {        long start = 1, end = x;        while (start + 1 < end) {            long mid = start + (end - start) / 2;            if (mid * mid <= x) {                start = mid;            } else {                end = mid;            }        }        if (end * end <= x) {            return (int)end;        }        return (int) start;    }
0 0
原创粉丝点击