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;
}
相关推荐
04aaaze11 小时前
C++(C转C++)
c语言·c++·算法
Swift社区11 小时前
LeetCode 429 - N 叉树的层序遍历
算法·leetcode·职场和发展
星释11 小时前
Rust 练习册 32:二分查找与算法实现艺术
开发语言·算法·rust
zl_vslam12 小时前
SLAM中的非线性优-3D图优化之四元数在Opencv-PNP中的应用(五)
人工智能·算法·计算机视觉
机器学习之心12 小时前
经典粒子群优化算法PSO-LSTM回归+SHAP分析+多输出+新数据预测!Matlab代码实现
算法·lstm·pso-lstm·shap分析
小青龙emmm13 小时前
2025级C语言第四次周测题解
c语言·开发语言·算法
树在风中摇曳13 小时前
【牛客排序题详解】归并排序 & 快速排序深度解析(含 C 语言完整实现)
c语言·开发语言·算法
minji...13 小时前
算法---模拟/高精度/枚举
数据结构·c++·算法·高精度·模拟·枚举
执笔论英雄14 小时前
【大模型训练】forward_backward_func返回多个micro batch 损失
开发语言·算法·batch
序属秋秋秋15 小时前
《Linux系统编程之进程基础》【进程优先级】
linux·运维·c语言·c++·笔记·进程·优先级