博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
69. Sqrt(x) (JAVA)
阅读量:4589 次
发布时间:2019-06-09

本文共 908 字,大约阅读时间需要 3 分钟。

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: 4Output: 2

Example 2:

Input: 8Output: 2Explanation: The square root of 8 is 2.82842..., and since              the decimal part is truncated, 2 is returned.
 
  • 用循环实现二分法
  • 用除法防止溢出 
class Solution {    public int mySqrt(int x) {        int left = 1;        int right = (x>>1) + 1;        int mid = 1;        while(left <= right){            mid = left + ((right-left) >> 1);            if(mid < x/mid){ //用除法防止溢出                left = mid+1;            }            else if(mid > x/mid){                right = mid-1;            }            else return mid;        }        return right;    }    }

 

转载于:https://www.cnblogs.com/qionglouyuyu/p/10912016.html

你可能感兴趣的文章
.NET 4.0 兼容 .NET 2.0 的方法
查看>>
1001 Maximum Multiple(2018 Multi-University Training Contest 1)
查看>>
对Java对象的认识与理解
查看>>
python——父类与子类的一些说明
查看>>
2019年3月3日 2018-2019-2 20189205《移动平台应用开发实践》第二周作业
查看>>
MySQL 性能优化--优化数据库结构之优化数据类型
查看>>
软件工程之软件需求分析
查看>>
Electron简介和安装使用
查看>>
Improving Visual C++ Debugging with Better Data Display
查看>>
JDBC
查看>>
workspace 配置
查看>>
C# 针对特定的条件进行锁操作,不用lock,而是mutex
查看>>
Spring归纳
查看>>
MyEclipse Web Project导入Eclipse Dynamic Web Project,无法部署到tomcat问 题
查看>>
24小时学通Linux内核之向内核添加代码
查看>>
python 函数
查看>>
Solr4.0 如何配置使用UUID自动生成id值
查看>>
Marketing™Series用户手册(Marketing™Series Manual)
查看>>
Java动态代理
查看>>
二维码开源库zbar、zxing使用心得
查看>>