Leetcode - Sqrt(x)

My code:

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

真是奇怪,我连这道题目都没做过。。。

这道题目就是binary search.
首先, 0,1的情况单独处理。
其次,拿到mid时,
不要 mid * mid
会溢出。这是我犯的错误。
要 x / mid去比较。

以前刷题,每次都是从做过的题目开始,狂刷一百多题。刷的永远都是会的题目。花的时间再多也永远不会有长进!!!

Anyway, Good luck, Richardo! — 09/01/2016

My code:

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

reference:
https://discuss.leetcode.com/topic/8680/a-binary-search-solution/2

牛顿迭代法

Anyway, Good luck, Richardo! — 09/28/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/7904449cca2c#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞