[LeetCode] 69. Sqrt(x)

题目链接:传送门

Description

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.

Solution

题意:

开方

思路:

二分,注意边界运算

class Solution {
public:
    int mySqrt(int x) {
        int l = 0, r = (1 << 31) - 2, mid;
        while (l < r) {
            mid = l + (r - l + 1) / 2;
            if (mid <= x / mid)  l = mid;
            else  r = mid - 1;
        }
        return l;
    }
};
posted @ 2018-02-25 01:27  酒晓语令  阅读(113)  评论(0编辑  收藏  举报