您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Sqrt(x)

2015-06-25 22:57 961 查看

Sqrt(x)

Implement
int 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);
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: