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;
}
相关推荐
来深圳5 分钟前
leetcode 739. 每日温度
java·算法·leetcode
yaoh.wang18 分钟前
力扣(LeetCode) 104: 二叉树的最大深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
egoist202330 分钟前
【Linux仓库】超越命令行用户:手写C语言Shell解释器,解密Bash背后的进程创建(附源码)
linux·c语言·bash·xshell·环境变量·命令行参数·内建命令
hetao173383730 分钟前
2025-12-21~22 hetao1733837的刷题笔记
c++·笔记·算法
醒过来摸鱼1 小时前
递归三种分类方法
算法
炽烈小老头1 小时前
【每天学习一点算法 2025/12/22】将有序数组转换为二叉搜索树
学习·算法
jghhh011 小时前
POCS(凸集投影)算法解决部分k空间数据缺失导致吉布斯伪影
算法
罗湖老棍子2 小时前
最小函数值(minval)(信息学奥赛一本通- P1370)
数据结构·c++·算法··优先队列·
LYFlied2 小时前
【每日算法】LeetCode 4. 寻找两个正序数组的中位数
算法·leetcode·面试·职场和发展
长安er2 小时前
LeetCode 62/64/5/1143多维动态规划核心题型总结
算法·leetcode·mybatis·动态规划