题目链接:传送门

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;
    }
};

相关文章:

  • 2021-11-09
  • 2021-06-14
  • 2022-01-22
  • 2021-07-07
  • 2022-12-23
  • 2021-11-29
猜你喜欢
  • 2021-11-23
  • 2021-10-07
  • 2021-07-31
  • 2021-12-08
相关资源
相似解决方案