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,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
随机推荐
- Delphi基础语法的学习笔记和注意事项总结
以下是我在自学Delphi的时候,对一些注意点的简单总结,并没有什么系统性可言,只是一个学习时顺手记下的笔记,主要为了当时加深对知识的印象,并没有希望能在以后的复习和使用Delphi中有什么多大的参考 ...
- SPOJ220 Relevant Phrases of Annihilation(后缀数组)
引用罗穗骞论文中的话: 先将n 个字符串连起来,中间用不相同的且没有出现在字符串中的字符隔开,求后缀数组.然后二分答案,再将后缀分组.判断的时候,要看是否有一组后缀在每个原来的字符串中至少出现两次,并 ...
- jQuery实现长按按钮触发事件的方法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Linggle: 英语写作学习搜索引擎
Linggle 搜索引擎是一个可用于英语写作的语法.句子工具,可帮助学习者分析更准确的英文写作建议,能够根据词性来推测短句和句子,可精准的分享出完整英文句子如何撰写. Linggle 是台湾学术团队研 ...
- 实现Activity刷新 (转)
目前刷新Acitivity,只想到几种方法.仅供参考,如果您有更好的方法,请赐教. 程序界面: 点击refresh view可以刷新界面,点击write content可以在EditText中自动写入 ...
- 删除表数据drop、truncate和delete的用法
说到删除表数据的关键字,大家记得最多的可能就是delete了 然而我们做数据库开发,读取数据库数据.对另外的两兄弟用得就比较少了 现在来介绍另外两个兄弟,都是删除表数据的,其实也是很容易理解的 老大- ...
- LoadRunner检查点
web_reg_find("Text=ABC", "SaveCount=abc_count", LAST);51Testing软件测试网V?2Rs.J Gmdw ...
- C#中Process类的使用
本文来自: http://www.cnblogs.com/kay/archive/2008/11/25/1340387.html Process 类的作用是对系统进程进行管理,我们使用Process类 ...
- Windows安装java
1.下载并安装java(jdk)//在官网下载即可——http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363. ...
- Angular.js 以及个人学习网站
Angular.js 教程 http://www.360doc.com/content/14/0414/15/14416931_368816305.shtml web前端学习: 慕课网:http:/ ...