69. Sqrt(x)

栏目: Java · 发布时间: 6年前

内容简介: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.

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.

Example 1:
Input: 4
Output: 2

Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

难度:easy

题目:

实现sqrt.

计算并返回x的开方,x保证非负整。

由于返回的类型是整数,十进制数只返回整数部分。

Runtime: 22 ms, faster than 30.19% of Java online submissions for Sqrt(x).

Memory Usage: 27 MB, less than 99.23% of Java online submissions for Sqrt(x).

class Solution {
    public int mySqrt(int x) {
        if (0 == x) {
            return x;
        }
        int left = 1, right = x, mid = 0, lastMid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (mid > x / mid) {
                right = mid - 1;
            } else {
                left = mid + 1;
                lastMid = mid;
            }
        }
        
        return lastMid;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

硅谷之谜

硅谷之谜

吴军 / 人民邮电出版社 / 2015-12-1 / 59.00

这是一本颠覆人们对信息时代的认识、对创新和创业的理解的好书。作者吴军通过介绍硅谷成功的秘诀,揭示了信息时代的特点和方法论。 近年来,吴军从技术和管理人员变成了投资人,他对IT领域,尤其是对科技创新因而有了更深入的了解。他根据这些年在硅谷所获得的第一手资料,结合自己的思考,回答了长期以来令大家深感困惑的一个不解之谜,那就是—为什么硅谷在全世界其他地区难以复制? 《硅谷之谜》从某种意义上讲......一起来看看 《硅谷之谜》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具