1,题目要求
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
实现一个sqrt函数。
2,题目思路
可以直接用遍历的办法来实现这样的sqrt函数,需要注意的是存储平方的值为long。
方法二也是遍历,不过检索的空间缩小了很多,因此速度也很快。
3,程序源码
方法1
关于ios::sync_with_stdio(false);和 cin.tie(0)加速c++输入输出流
static vector<string> strs = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
return vector<string>{};
}();
//加了上面一段代码,速度直接从42ms下降到了28ms,很神奇!
//在C++类的输入输出中,cin和cout效率比较低,而造成额外的时间消耗
//cin,cout之所以效率低,是因为先把要输出的东西存入缓冲区,再输出,导致效率降低,而这段语句可以来打消iostream的输入 输出缓存,可以节省许多时间,使效率与scanf与printf相差无几,还有应注意的是scanf与printf使用的头文件应是stdio.h而不是 iostream。
class Solution {
public:
int mySqrt(int x) {
long long s = 0, i =0;
while(s<=x){
i++;
s = i*i;
}
return i-1;
}
};
方法2:
static vector<string> strs = [](){
std::ios::sync_with_stdio(false);
std::cin.tie(0);
return vector<string>{};
}();
class Solution {
public:
int mySqrt(int x) {
long r = x;
long a = x;
while(r * r > a) {
r = (r + a / r) / 2;
}
return r;
}
};