问题描述
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
题目链接:
思路分析
实现开平方功能,要求返回平方根的整数部分。
代码
class Solution {
public:
int mySqrt(int x) {
double a = sqrt(x);
int b = (int)a;
return b;
}
};
时间复杂度:未知
反思
一开始用float发现精度不够,后来使用double就可以了,一时间不知意义何在。后来看disscussion才知道,要用折半搜索来实现,修改代码:
class Solution {class Solution {
public:
int mySqrt(int x) {
int high = x, low = 0, mid = high/2;
while(pow(mid,2) > x || pow(mid + 1, 2) <= x){
mid = (high + low)/2;
if (pow(mid,2) > x)
high = mid - 1;
else if(pow(mid + 1, 2) <= x)
low = mid + 1;
else if (pow(mid,2) == x)
break;
}
return mid;
}
};
时间复杂度:O(logn)