文章目录
leetcode69:69. x 的平方根
题目描述
实现 int sqrt(int x)
函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
Example
输入: 8
输出: 2
solution idea
sqrt 函数
class Solution {
public:
/*
** sqrt 函数
*/
int mySqrt(int x) {
return int(sqrt(x));
}
Newton 迭代法
这里要将 x0,x1
定义为double
,防止整数溢出
class Solution {
public:
/*
** Newton 迭代法 Xk+1=1/2(Xk+X/Xk)
**
*/
int mySqrt(int x) {
if (x<2) return x;
double x0=1,x1=(x0+x/x0)/2;
while(abs(x0-x1)>=1)
{
x0=x1;
x1=(x0+x/x0)/2;
}
return int(x1);
}
};
二分法
class Solution {
public:
/*
** 二分法
*/
int mySqrt(int x) {
if (x<2) return x;
int left=2,right=x/2,mid=(left+right)/2;
while(left<=right)
{
if(x/mid==mid) return mid;
else if((mid-x/mid) <0)
{
left=mid+1;
mid=(left+right)/2;
}
else
{
right=mid-1;
mid=(left+right)/2;
}
}
return int(mid);
}
};
参考文献
- c++ prime 第5版