一、题目
给你一个非负整数
x
,计算并返回x
的 算术平方根 。由于返回类型是整数,结果只保留 整数部分 ,小数部分将被 舍去 。
注意:不允许使用任何内置指数函数和算符,例如
pow(x, 0.5)
或者x ** 0.5
。
二、解答
说实话,刚看到这个题目的时候我人傻了, 硬是没想到该怎么办。于是首先弄了一个“作弊式”的办法,效果相当好啊,不过不符合题意。(悲
class Solution {
public:
int mySqrt(int x) {
return sqrt(x);
}
};
于是我左思又想,盯着题目看了又看,发现——既然题目要求只保留整数,那么我就可以通过判断一个数在哪两个整数的平方之间,从而得出结果(俗称“暴力解法”)。代码如下。
class Solution {
public:
int mySqrt(int x) {
double j=1;//必须用double,int的范围太小了
while(j&&x){
if(x>=j*j && x<(j+1)*(j+1)){
return j;
}
else{
j++;
}
}
return x;
}
};
运行结果如下。
当然,这种解法的耗时算比较慢的,下面给出更优解。
三、优化解
代码如下:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) {
return 0;
}
int ans = exp(0.5 * log(x));
return ((long long)(ans + 1) * (ans + 1) <= x ? ans + 1 : ans);
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/sqrtx/solutions/238553/x-de-ping-fang-gen-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
其中有一个“long long”的类型,其实就是八位整型。这篇文章中有详细介绍。
同样是查找,方法二就比暴力解法快多了。
关于二分法的详细介绍,这位博主讲得很好——http://t.csdnimg.cn/DYxGz。
代码如下:
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x, ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if ((long long)mid * mid <= x) {
ans = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
return ans;
}
};
作者:力扣官方题解
链接:https://leetcode.cn/problems/sqrtx/solutions/238553/x-de-ping-fang-gen-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。