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;
}
相关推荐
natide11 分钟前
表示/嵌入差异-7-间隔/边际对齐(Alignment Margin)
人工智能·深度学习·算法·机器学习·自然语言处理·知识图谱
在风中的意志12 分钟前
[数据库SQL] [leetcode-584] 584. 寻找用户推荐人
数据库·sql·leetcode
毅炼16 分钟前
hot100打卡——day08
java·数据结构·算法·leetcode·深度优先
l1t27 分钟前
DeepSeek总结的算法 X 与舞蹈链文章
前端·javascript·算法
gihigo199828 分钟前
水声信号处理中DEMON谱分析的原理、实现与改进
算法·信号处理
歌_顿34 分钟前
微调方法学习总结(万字长文!)
算法
Dillon Dong39 分钟前
从C到Simulink: ARM Compiler 5 (RVDS) 为什么simulink 不能使用arm编译
c语言·arm开发·simulink
@小码农40 分钟前
202512 电子学会 Scratch图形化编程等级考试四级真题(附答案)
java·开发语言·算法
mit6.8241 小时前
右端点对齐|镜像复用
算法
黎雁·泠崖1 小时前
Java底层探秘进阶:JIT汇编逐行拆解!Java方法栈帧与C语言深度对标
java·c语言·汇编