LeetCode 69 Sqrt(x)

简介: 题目描述: Implement int sqrt(int x). Compute and return the square root of x. 题目翻译:输入x,返回sqrt(x); C语言版: int mySqrt(int x) { int t...

题目描述:

Implement int sqrt(int x).

Compute and return the square root of x.


题目翻译:输入x,返回sqrt(x);


C语言版:

int mySqrt(int x) {
    int t, l, r, mid;
    l = 1;
    r = x>>1;
    if (x < 2) return x;
    while(l <= r){
        mid = (l + r) >> 1;
        if (mid == x/mid) return mid;
        else if(mid < x/mid){
            l = mid + 1;
        }
        else r = mid - 1;
    }
    return r;
}
看似一个简单的二分查找,其实里面也有很多细节要注意

比如:l的初始化问题,以前习惯性初始化为0,在这里就不可以,比如X==2的时候,会出现除0错误

还有就是一些开平方的结果是小数的,在这里当然就要输出整数,那么,最后return哪一个值呢?

一开始我固执的以为应该是左边的指针较小,应该返回左边的指针l,错了才发现,跳出循环的时候

左边的指针已经大于右边的指针了,因此应该返回右边的指针r!

目录
相关文章
|
Python
LeetCode 69. Sqrt(x)
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
100 0
|
Java 测试技术 C++
LeetCode 69. Sqrt(x)--(数组)--二分法查找 --简单
Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
108 0
LeetCode 69. Sqrt(x)--(数组)--二分法查找 --简单
LeetCode 69. Sqrt(x)
实现int sqrt(int x). 计算并返回x的平方根,其中x保证为非负整数. 由于返回类型是整数,因此将截断十进制数字,并仅返回结果的整数部分.
68 0
LeetCode 69. Sqrt(x)
☆打卡算法☆LeetCode 69、Sqrt(x) 算法解析
“给定一个非负整数,计算并返回x的算术平方根。”
[LeetCode]--69. Sqrt(x)
Implement int sqrt(int x). Compute and return the square root of x. 我采用的是二分法。每次折中求平方,如果大了就把中值赋给大的,如果小了就把中值赋给小的。 public int mySqrt(int x) { long start = 1, end = x; while
843 0
|
17天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
17天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
18天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值