【LeetCode 0069】【二分查找】求平方根

  1. Sqrt(x)

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

  • For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Example 1:

**Input:** x = 4
**Output:** 2
**Explanation:** The square root of 4 is 2, so we return 2.

Example 2:

**Input:** x = 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

Constraints:

  • 0 <= x <= 2^31 - 1
JavaScript Solution
/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    /*
    let ans = 0;
    while(x  >= (ans+1)**2){
        ans++;
    }
    return ans
    */
    let f = 0
    for(let s = x; s > 0; s = ~~(s/2)){
        while((f+s)*(f+s)<=x)f+=s
    }
    return f
};

相关推荐

  1. LeetCode 0069】【二分查找平方根

    2024-07-18 13:40:01       24 阅读
  2. 力扣69 x的平方根 二分查找平方根 C语言

    2024-07-18 13:40:01       25 阅读
  3. LeetCode | 数组 | 二分查找 | 69. x 的平方根【C++】

    2024-07-18 13:40:01       41 阅读
  4. 【题解】leetcode---69. x 的平方二分查找入门)

    2024-07-18 13:40:01       55 阅读
  5. 【算法】平方根 - 二分法/牛顿迭代

    2024-07-18 13:40:01       34 阅读
  6. leetcode704. 二分查找

    2024-07-18 13:40:01       57 阅读
  7. Leetcode:704. 二分查找

    2024-07-18 13:40:01       74 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 13:40:01       70 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 13:40:01       74 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 13:40:01       62 阅读
  4. Python语言-面向对象

    2024-07-18 13:40:01       72 阅读

热门阅读

  1. 密码学原理精解【8】

    2024-07-18 13:40:01       21 阅读
  2. 中电金信-杭州工商银行|面试真题|2024年

    2024-07-18 13:40:01       24 阅读
  3. Vue学习---vue 防抖处理函数,是处理什么场景

    2024-07-18 13:40:01       24 阅读
  4. k8s logstash多管道配置

    2024-07-18 13:40:01       21 阅读