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;
}
相关推荐
liliangcsdn7 分钟前
如何对IC时间序列进行汇总统计分析示例
人工智能·算法·机器学习
土司大王16 分钟前
LeetCode hot100——缺失的第一个正数
数据结构·算法·leetcode
布莱克60521 分钟前
strcpy 函数详解:作用、用法与安全缺陷
c语言·开发语言·c++·安全
Cccp.12323 分钟前
【leetcode】(二)认识O(NlogN)的排序
算法·leetcode
明月_清风44 分钟前
算法时间复杂度:给小白的一堂"算快慢"课
后端·算法
DDXYcoder1 小时前
内存函数与数据存储
c语言
vivo互联网技术1 小时前
TinySR:面向真实世界图像超分辨率的轻量级扩散模型
人工智能·算法
不会就选b1 小时前
数据结构之栈的算法题(OJ)
linux·数据结构·算法
人工智能培训2 小时前
人工智能性别与地域偏见的成因及消解路径
大数据·人工智能·算法·生活
鹿角片ljp2 小时前
LeetCode 56:合并区间复盘|从排序思维到 List<int[]> 的简洁写法
算法·leetcode·list