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;
}
相关推荐
sali-tec4 分钟前
C# 基于OpenCv的视觉工作流-章25-ORB特征点
图像处理·人工智能·opencv·算法·计算机视觉
jghhh011 小时前
LT喷泉码编解码的MATLAB实现
数据库·算法·matlab
被遗忘在角落的死小孩1 小时前
抗量子 Winternitz One Time Signature(OTS) 算法学习
学习·算法·哈希算法
浅念-1 小时前
C++ :类和对象(4)
c语言·开发语言·c++·经验分享·笔记·学习·算法
YunchengLi1 小时前
【移动机器人运动规划】5 基于优化的轨迹规划 Part2
算法·机器人
道法自然|~1 小时前
BugkuCTF栅栏密码解题记录(原理+C语言实现)
c语言·开发语言
yuuki2332331 小时前
【C++】模拟实现 AVL树
java·c++·算法
dog2502 小时前
阿基米德的有限步逼近思想求圆面积
算法
想做功的洛伦兹力12 小时前
2026/2/13日打卡
算法
仟濹2 小时前
【算法打卡day7(2026-02-12 周四)算法:BFS and BFS】 3_卡码网107_寻找存在的路线_并查集
数据结构·算法·图论·宽度优先