LeetCode //C - 69. Sqrt(x)

69. 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 0 <= x <= 2^{31} - 1 0<=x<=231−1

From: LeetCode

Link: 69. Sqrt(x)


Solution:

Ideas:
  • We first handle the special case of x being 0.
  • We define left and right to represent the range of possible square root values.
  • Inside the while loop, we calculate the mid of the range.
  • We compare mid * mid with x. To avoid integer overflow, we use mid <= x / mid.
  • If mid * mid is less than or equal to x, we update left and ans.
  • If mid * mid is greater than x, we adjust right.
  • When the loop finishes, ans contains the floor of the square root of x.
Code:
c 复制代码
int mySqrt(int x) {
    if (x == 0) return 0;
    int left = 1, right = x, ans;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (mid <= x / mid) { // To avoid overflow
            left = mid + 1;
            ans = mid;
        } else {
            right = mid - 1;
        }
    }
    return ans;
}
相关推荐
憨憨崽&1 小时前
C语言、Java、Python 的选择与未来发展以及学习路线
java·c语言·python
地平线开发者1 小时前
mul 与 reduce_sum 的优化实例
算法·自动驾驶
坚持编程的菜鸟1 小时前
LeetCode每日一题——Pow(x, n)
c语言·算法·leetcode
csdn_aspnet1 小时前
分享MATLAB在数据分析与科学计算中的高效算法案例
算法·matlab·数据分析
白云千载尽1 小时前
moveit使用和机器人模型与状态--正向运动学和逆向运动学分析(四)
算法·机器人·逆运动学·moveit·正向运动学
我想吃余2 小时前
【0基础学算法】前缀和刷题日志(三):连续数组、矩阵区域和
算法·矩阵·哈希算法
perseveranceX2 小时前
插入排序:扑克牌式的排序算法!
c语言·数据结构·插入排序·时间复杂度·排序稳定性
2501_938773992 小时前
文档搜索引擎搜索模块迭代:从基础检索到智能语义匹配升级
人工智能·算法·搜索引擎
CS创新实验室2 小时前
典型算法题解:长度最小的子数组
数据结构·c++·算法·考研408
我有一些感想……2 小时前
浅谈 BSGS(Baby-Step Giant-Step 大步小步)算法
c++·算法·数论·离散对数·bsgs