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;
}
相关推荐
pianmian11 小时前
python数据结构基础(7)
数据结构·算法
闲晨1 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
好奇龙猫3 小时前
【学习AI-相关路程-mnist手写数字分类-win-硬件:windows-自我学习AI-实验步骤-全连接神经网络(BPnetwork)-操作流程(3) 】
人工智能·算法
sp_fyf_20244 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-11-01
人工智能·深度学习·神经网络·算法·机器学习·语言模型·数据挖掘
香菜大丸4 小时前
链表的归并排序
数据结构·算法·链表
jrrz08284 小时前
LeetCode 热题100(七)【链表】(1)
数据结构·c++·算法·leetcode·链表
oliveira-time4 小时前
golang学习2
算法
南宫生5 小时前
贪心算法习题其四【力扣】【算法学习day.21】
学习·算法·leetcode·链表·贪心算法
懒惰才能让科技进步6 小时前
从零学习大模型(十二)-----基于梯度的重要性剪枝(Gradient-based Pruning)
人工智能·深度学习·学习·算法·chatgpt·transformer·剪枝
DARLING Zero two♡6 小时前
关于我、重生到500年前凭借C语言改变世界科技vlog.16——万字详解指针概念及技巧
c语言·开发语言·科技