Leetcode Sqrt(x)
(x0 越接近S的平方根越好)


class Solution {
public:
int sqrt(double x) {
if(x == ) return ;
double root = x/, tolerance = 1.0e-2;
do{
root=(root+x/root)/;
}while(abs(root*root-x)>tolerance);
return root;
}
};
这题感觉题目有问题,返回的平方根竟然是整数,
另一种方法是是用二分搜索
class Solution {
public:
int sqrt(int x) {
if(x < ) return x;
int left = , right = x;
while(left <= right){
int mid = (right+left)/;
if(mid < x/mid) left = mid+;
else if(x/mid < mid ) right = mid-;
else return mid;
}
return right;
}
};
如果题目要求的时浮点数可以考虑利用浮点数二分搜索
Leetcode Sqrt(x)的更多相关文章
- [LeetCode] Sqrt(x) 求平方根
Implement int sqrt(int x). Compute and return the square root of x. 这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方, ...
- [leetcode]Sqrt(x) @ Python
原题地址:https://oj.leetcode.com/problems/sqrtx/ 题意: Implement int sqrt(int x). Compute and return the s ...
- LeetCode: Sqrt
Title: Implement int sqrt(int x). Compute and return the square root of x. 思路:这个平方根肯定是在[1,x]之间,所以在这个 ...
- leetcode—sqrt
1.题目描述 Implement int sqrt(int x). Compute and return the square root of x. 2.解法分析 很明显,用二分搜索可解,但是 ...
- LeetCode:Sqrt(x) 解题报告
Sqrt(x) Implement int sqrt(int x). Compute and return the square root of x. SOLUTION 1: 参见:二分法总结,以及模 ...
- LeetCode——Sqrt(x)
Description: Implement int sqrt(int x). Compute and return the square root of x. 好好学习数学还是非常有用的,牛顿迭代法 ...
- [Leetcode] sqrt 开根号
Implementint sqrt(int x). Compute and return the square root of x. 题意:求根号下x 的值 思路:使用二分搜索.先定义x平方根的取值区 ...
- [LeetCode] Sqrt(x) 二分搜索
Implement int sqrt(int x). Compute and return the square root of x. Hide Tags Math Binary Search ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
随机推荐
- CLR via C#(08)-操作符
对于操作符,我们并不陌生,例如+,-,*,%等二元操作符,以及++,!等一元操作符.但是对于非基元类型,我们需要通过一些自定义方法才能使用这些操作符.今天主要和大家分享关于操作符重载和转换操作符的知识 ...
- MVC公开课 – 1.基础 (2013-3-15广州传智MVC公开课)
1.MVC设计模式 Model 是指 要处理的业务代码和数据操作代码 View 视图 主要是指的 跟用户打交道 并能够展示数据 Controller 看成是 Model和View的桥梁 优点: 1 ...
- 【C#】 用Route进行URL重写
在.NET Framework 4中,微软推出了Route机制.这种机制不仅在MVC中大量运用,在WebForm中也可以使用. 和Contex.RewritePath()一样,Route功能也是写在G ...
- jQuery Mobile学习之grid、等待显示的ajax效果、页面跳转、页面跳转传递参数等(二)
Index.cshtml <!-- Start of second page --> <section data-role="page" id="bar ...
- 【翻译二十】-java线程池
Thread Pools Most of the executor implementations in java.util.concurrent use thread pools, which co ...
- 攻城狮在路上(壹) Hibernate(十三)--- Hibernate的检索方式(上)
Hibernate提供了以下几种检索对象的方式: A.导航对象图检索方式. B.OID检索方式.Session.get() load(); C.HQL检索方式.Query. D.QBC检索方式.Que ...
- Auto Layout
Auto Layout XCode5+ Auto Layout Concepts 核心的概念是约束. Constraint Basics Constant value Relation Priorit ...
- Bat脚本实现MySQL数据库SQL文件备份
@echo offecho 在线兑奖系统自动备份脚本(请勿关闭) 联系人: 电话::loopset /a "FDate=%date:~,4%%date:~5,2%%date:~8,2%&q ...
- gnuplot安装问题(set terminal "unknown")
今天在系统同上要装个gnuplot,原来用的都是拷好的虚拟机.这也是第一次装.本来以为分分钟的事,却不料遇到不少麻烦.记录一下,供大家参考 一,快速开始安装 ubuntu下那自然是: sudo apt ...
- JavaScript前端框架的思考
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:现在JavaScript前端框架层出不穷,尤其Angular进入到2.x时候之后,我们 ...