LeetCode——Sqrt(x)
Description:
Implement int sqrt(int x)
.
Compute and return the square root of x.
好好学习数学还是非常有用的,牛顿迭代法求解。
计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示。
首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1。
同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2。
以此类推。
以这样的方式得到的xi会无限趋近于f(x)=0的解。
判断xi是否是f(x)=0的解有两种方法:
一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。
public class Solution {
public int mySqrt(int x) {
if (x ==0)
return 0;
double pre;
double cur = 1;
do
{
pre = cur;
cur = x / (2 * pre) + pre / 2.0;
} while (Math.abs(cur - pre) > 0.00001);
return (int) cur; }
}
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(x)
参考Babylonian method (x0 越接近S的平方根越好) class Solution { public: int sqrt(double x) { ) ; , tolerance ...
- 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 开根号
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,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
随机推荐
- sizeof数据对齐问题
#include <iostream> using namespace std; struct A1 { int a; static int b; }; struct A2 { int a ...
- Android——对话框1(一般、选择、自定义、进度条)
xml <Button android:layout_width="match_parent" android:layout_height="wrap_conten ...
- Spring引入配置文件
1.spring.xml加载映射的配置配置文件 <!--采用这种方式简化配置文件--> <context:property-placeholder location="cl ...
- DataGridView:根据条件改变单元格的颜色
根据条件改变DataGridView行的颜色可以使用RowPrePaint事件. 示例程序界面如下: 示例程序代码如下: using System; using System.Collections. ...
- PHP变量解析顺序variables_order
转载自:http://blog.csdn.net/knight0450/article/details/4291556 故事从一个有点诡异的BUG开始,后台一个使用频率不是很高的广告提交功能有时候会莫 ...
- tp-02 四种url访问的方式
:http://localhost/index.php?m=模块&c=控制器&a=操作方法 [get模式] :http://localhost/index.php/模块[模块文件夹]/ ...
- R语言扩展包dplyr笔记
引言 2014年刚到, 就在 Feedly 订阅里看到 RStudio Blog 介绍 dplyr 包已发布 (Introducing dplyr), 此包将原本 plyr 包中的 ddply() 等 ...
- sixxpack破解的文章!【转】
星期天闲着没事玩游戏,玩游戏不能无外挂.于是百度了半天,找到了一个,看介绍貌似不错,就下载了下来.一看,竟然是用.net写的,下意识地Reflector了一下.发现竟是一个叫actmp的程序集.如图: ...
- 说说自己对hibernate一级、二级、查询、缓存的理解。
说说自己对hibernate一级.二级.查询.缓存的理解. 2016-03-14 21:36 421人阅读 评论(0) 收藏 举报 分类: web开发(19) 版权声明:本文为博主原创文章,未经博 ...
- 【Java面试题】49 垃圾回收的优点和原理。并考虑2种回收机制。
1.Java语言最显著的特点就是引入了垃圾回收机制,它使java程序员在编写程序时不再考虑内存管理的问题. 2.由于有这个垃圾回收机制,java中的对象不再有“作用域”的概念,只有引用的对象才有“作用 ...