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;
}
相关推荐
Yhame.7 分钟前
【使用层次序列构建二叉树(数据结构C)】
c语言·开发语言·数据结构
雾月5532 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++1 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
杜小暑2 小时前
动态内存管理
c语言·开发语言·动态内存管理
YuforiaCode2 小时前
第十二届蓝桥杯 2021 C/C++组 直线
c语言·c++·蓝桥杯
知来者逆2 小时前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr
阿让啊2 小时前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
এ᭄画画的北北2 小时前
力扣-160.相交链表
算法·leetcode·链表
拾忆-eleven2 小时前
C语言实战:用Pygame打造高难度水果消消乐游戏
c语言·python·pygame
爱研究的小陈3 小时前
Day 3:数学基础回顾——线性代数与概率论在AI中的核心作用
算法