[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

Implement int sqrt(int x).

Compute and return the square root of x.

我采用的是二分法。每次折中求平方,如果大了就把中值赋给大的,如果小了就把中值赋给小的。

public int mySqrt(int x) {
        long start = 1, end = x;
        while (start + 1 < end) {
            long mid = start + (end - start) / 2;
            if (mid * mid <= x) {
                start = mid;
            } else {
                end = mid;
            }
        }

        if (end * end <= x) {
            return (int)end;
        }

        return (int) start;
    }
目录
相关文章
|
Python
LeetCode 69. Sqrt(x)
给你一个非负整数 x ,计算并返回 x 的 算术平方根 。
97 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.
104 0
LeetCode 69. Sqrt(x)--(数组)--二分法查找 --简单
LeetCode 69. Sqrt(x)
实现int sqrt(int x). 计算并返回x的平方根,其中x保证为非负整数. 由于返回类型是整数,因此将截断十进制数字,并仅返回结果的整数部分.
64 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. 题目翻译:输入x,返回sqrt(x); C语言版: int mySqrt(int x) { int t...
864 0
|
5天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
5天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
12 0