Sqrt(x) Leetcode

Implement int sqrt(int x).

Compute and return the square root of x.

小小的一道题竟然做了半天。。。= =

乘法啊加法啊reverse这些一定要考虑到越界的问题。

另外可以使用start + 1 < end的条件,这个时候一般跳出循环之后要判断一下边界值。

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

 

posted @ 2017-01-27 05:58  璨璨要好好学习  阅读(100)  评论(0编辑  收藏  举报