您的位置:首页 > 其它

leetcode 69. Sqrt(x)

2017-09-06 09:02 555 查看
Implement int sqrt(int x).

Compute and return the square root of x.

这道题考察的就是sqrt函数的实现,我是网上找到的一个教程做得,它适用的是牛顿迭代法直接迭代,我也不太懂,直接拿来用了。

代码如下:

public class Solution
{
public int mySqrt(int x)
{
//牛顿迭代法
long y=x;
while(y*y>x)
y=(y+x/y)/2;

return (int)y;
}
}


下面是C++的做法,我就是按照cmath库函数做的

代码如下:

#include <iostream>
#include <cmath>
using namespace std;

class Solution
{
public:
int mySqrt(int x)
{
return (int)(sqrt(x));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode