69. Sqrt(x)

来源:互联网 发布:办公软件基础教程 编辑:程序博客网 时间:2024/06/05 03:34

Implement int sqrt(int x).

Compute and return the square root of x.

可以用binary search,适合用upperbound的模板,模板:Binary Search - 二分搜索。因为num除了0、1外,sqrt的结果都会<=num/2,这样把start设成0,end设成n/2+2,条件设成mid>x/mid。注意这里不要用mid*mid>x,因为mid*mid会溢出。代码如下:

public class Solution {    public int mySqrt(int x) {        int start = 0, end = x / 2 + 2;        while (start + 1 < end) {            int mid = start + (end - start) / 2;            //don't use mid*mid > x, it will overflow            if (mid > x / mid) {                end = mid;            } else {                start = mid;            }        }        return end - 1;    }}

0 0
原创粉丝点击