实现int sqrt(int x)
函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:
输入: 4
输出: 2
示例 2:
输入: 8
输出: 2
说明: 8 的平方根是 2.82842...,
由于返回类型是整数,小数部分将被舍去。
牛顿迭代法求解,原理解析:牛顿开方法的算法及其原理
答案
class Solution {
public:
int mySqrt(int x) {
if(x<=0) return 0;
else
{
double eps = 0.0000000000001;
double t = x;
while (fabs(t - x/t) > eps * t) {
t = (t + x / t) / 2;
}
return floor(t);
}
}
};
或者牛顿迭代法另一版代码如下:
class Solution {
public:
int mySqrt(int x) {
long a = x;
while(a * a > x)
{
a = (a + x / a) / 2;
}
return int (a);
}
};
也可以用二分查找法思路求解,思路如下:
1.猜测目标值x的平方根为当前子序列的中点k,求k的平方和x的大小是否相等。
2.如果猜对了,直接返回;
3.若猜的小于或等于目标值,说明此时k可用,则记录当前中点k,在中点的右侧继续猜测;
4.若猜的大于目标值,说明此时k不可用,则在中点的左侧继续猜。
class Solution {
public:
bool guess(int k, int x){
return (long)k * k <= x;
}
int mySqrt(int x) {
if(x == 0){
return 0;
}
if(x == 1){
return 1;
}
int L = 1, R = x;
int ans = 0;
while(L <= R){
int mid = L + (R - L)/2;
if(guess(mid, x)){
ans = mid;
L = mid + 1;
}else{
R = mid - 1;
}
}
return ans;
}
};
再追加一个返回double类型的:
//对于非负数x,求它的平方根sqrt(x),误差小于1e-3
#include <iostream>
#include <cmath>
using namespace std;
double my_sqrt(double &input) {
double res = 0.0;
if(input < res)
{
return res;
}
double l = 0.0;
double h = input;
while(l < h)
{
double mid = l + (h - l) / 2;
if(mid * mid < input) {
res = mid;
l = mid;
}
else {
h = mid;
}
if(abs(mid * mid - input) < 0.000001) {
break;
}
}
return res;
}
int main()
{
double t = 9.2;
double res = my_sqrt(t);
double f = res * res;
std::cout << "res is: " << res << std::endl;
std::cout << "f is: " << f << std::endl;
return 0;
}