[LeetCode][JavaScript]Sqrt(x)
2015-06-25 22:57
961 查看
Sqrt(x)
Implementint sqrt(int x).
Compute and return the square root of x.
https://leetcode.com/problems/sqrtx/
对于数学早就还给老师的我,开方真是跪了。
查了一下是牛顿迭代法(什么鬼。
先随便猜一个数,我就猜了三分之一,然后套用公式。
candidate = (candidate + x / candidate) / 2;
题目要求返回int型,我精度就算到了0.01。
查牛顿迭代法的途中看到一篇文章很有意思。
http://www.guokr.com/post/90718/
/** * @param {number} x * @return {number} */ var mySqrt = function(x) { var candidate = x / 3; while(Math.abs(x - candidate * candidate) > 0.01){ candidate = (candidate + x / candidate) / 2; } return parseInt(candidate); };
相关文章推荐
- javaScript语法入门
- [LeetCode][JavaScript]Pow(x, n)
- jsp遍历读取xml值
- 读《高性能javascript》笔记(一)
- javascript深入理解js闭包
- js 大小写转换
- 【HM】第2课:JavaScript基础
- Javascript 多浏览器兼容性问题及解决方案
- 通过JS设置一个元素的文本
- NPOI导出Excel(异步请求)
- js如果你想删除您问
- js参数arguments的理解
- php面试题之二——Javascript(基础部分)
- Javascript执行顺序详解
- JavaScript之AJAX实现二级联动菜单(jsp+js+servlet+xml)
- 因一段JavaScript代码引发的闲扯
- JSON 数组格式
- Ext JS Tips
- JSFIDDLE 动力 Threejs 功能探秘
- JS练习:Dom节点的CRUD操作