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;
}
相关推荐
m0_7482500324 分钟前
C++ 信号处理
c++·算法·信号处理
Ro Jace25 分钟前
电子侦察信号处理流程及常用算法
算法·信号处理
yuyanjingtao37 分钟前
动态规划 背包 之 凑钱
c++·算法·青少年编程·动态规划·gesp·csp-j/s
ALzc1 小时前
深度剖析EtherCAT FOE功能:ARM固件升级的数据传输与状态机实现
c语言·stm32·ethercat·foe
core5122 小时前
SGD 算法详解:蒙眼下山的寻宝者
人工智能·算法·矩阵分解·sgd·目标函数
Ka1Yan2 小时前
[链表] - 代码随想录 707. 设计链表
数据结构·算法·链表
scx201310042 小时前
20260112树状数组总结
数据结构·c++·算法·树状数组
FastMoMO2 小时前
Qwen3-VL-2B 在 RK3576 上的部署实践:RKNN + RKLLM 全流程
算法
光算科技2 小时前
AI重写工具导致‘文本湍流’特征|如何人工消除算法识别标记
大数据·人工智能·算法
宵时待雨2 小时前
数据结构(初阶)笔记归纳3:顺序表的应用
c语言·开发语言·数据结构·笔记·算法