LeetCode69. 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 <= 231 - 1

二、题解

class Solution {
   
public:
    int mySqrt(int x) {
   
        int l = 0,r = x,res = 0;
        while(l <= r){
   
            int mid = l + ((r-l) >> 1);
            if((long long)mid * mid <= x){
   
                res = mid;
                l = mid + 1;
            }
            else{
   
                r = mid - 1;
            }
        }
        return res;
    }
};

相关推荐

  1. LeetCode69. Sqrt(x)

    2024-01-25 17:48:03       53 阅读
  2. 69. Sqrt(x)

    2024-01-25 17:48:03       29 阅读
  3. LeetCode题(66,69,35,88)--《c++》

    2024-01-25 17:48:03       28 阅读
  4. leetcode69 x 的平方根

    2024-01-25 17:48:03       51 阅读
  5. 69.x 的平方根(力扣LeetCode

    2024-01-25 17:48:03       51 阅读
  6. LeetCode66. Plus One

    2024-01-25 17:48:03       59 阅读

最近更新

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

    2024-01-25 17:48:03       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-25 17:48:03       107 阅读
  3. 在Django里面运行非项目文件

    2024-01-25 17:48:03       90 阅读
  4. Python语言-面向对象

    2024-01-25 17:48:03       98 阅读

热门阅读

  1. 代码随想录算法训练营29期Day29|LeetCode 491,46,47

    2024-01-25 17:48:03       61 阅读
  2. 数据结构刷题笔记

    2024-01-25 17:48:03       57 阅读
  3. 杂七杂八的命令

    2024-01-25 17:48:03       57 阅读
  4. 【Ubuntu】systemctl 命令

    2024-01-25 17:48:03       60 阅读
  5. Vue3全局组件和自定义指令

    2024-01-25 17:48:03       64 阅读
  6. Unity串口通信教程:基础知识和实践指南

    2024-01-25 17:48:03       61 阅读
  7. 阿里云对象存储(OSS)服务

    2024-01-25 17:48:03       62 阅读
  8. Vue 中如何模块化使用 Vuex

    2024-01-25 17:48:03       54 阅读
  9. redis漏洞研究

    2024-01-25 17:48:03       61 阅读
  10. 用Python画出漂亮的地图

    2024-01-25 17:48:03       58 阅读