美文网首页
69. Sqrt(x)

69. Sqrt(x)

作者: 衣介书生 | 来源:发表于2018-04-13 17:59 被阅读9次

    题目分析

    Implement int sqrt(int x).

    Compute and return the square root of x.

    x is guaranteed to be a non-negative integer.

    Example 1:

    Input: 4
    Output: 2
    

    Example 2:

    Input: 8
    Output: 2
    

    Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

    这里采用二分法的方法来解这道题目。

    代码

    class Solution {
        public int mySqrt(int x) {
            if(x <= 0) return 0;
            int low = 1, high = x;
            while(low <= high) {
                long mid = (high - low) / 2 + low;
                if(mid * mid == x) {
                    return (int)mid;
                } else if(mid * mid < x) {
                    low = (int)mid + 1;
                } else {
                    high = (int)mid - 1;
                }
            }
            return low - 1;
        }
    }
    

    相关文章

      网友评论

          本文标题:69. Sqrt(x)

          本文链接:https://www.haomeiwen.com/subject/rklhkftx.html