美文网首页二分
【leetcode】69. Sqrt(x)(二分)

【leetcode】69. Sqrt(x)(二分)

作者: 邓泽军_3679 | 来源:发表于2019-05-06 11:48 被阅读1次

    1、题目描述

    Implement int sqrt(int x).

    Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

    Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

    Example 1:

    Input: 4
    Output: 2
    Example 2:

    Input: 8
    Output: 2
    Explanation: The square root of 8 is 2.82842..., and since
    the decimal part is truncated, 2 is returned.

    2、问题描述:

    • 实现求平方根的操作。
    • 如果是小数,返回整数部分。

    3、问题关键:

    • 二分法,依次逼近。

    4、C++代码:

    class Solution {
    public:
        int mySqrt(int x) {
            int l = 0, r = x;
            while(l < r) {
                int mid = l + 1ll + r >> 1;
                if (mid <= x / mid) l = mid;//这个地方注意是<=,不要忘记等号。
                else r = mid - 1;
            }
            return l;
        }
    };
    

    相关文章

      网友评论

        本文标题:【leetcode】69. Sqrt(x)(二分)

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