题目描述:
Implement int sqrt(int x)
.
Compute and return the square root of x.
跟前面的几道题目类似,思路就是从ret=1开始不断增大来找ret * ret 最接近x的值,通过左移操作将原本O(n)的复杂度降到O(logn)。需要注意的还是整数越界的问题,一开始我循环终止条件用的ret * ret > x,会出现越界情况,解决方法就是改为ret > x / ret。代码如下:
class Solution {
public:
int sqrt(int x) {
int ret(0), curr(1);
while (1){
int curr(1);
int xx = x;
while (ret + curr <= xx / (ret + curr))
curr <<= 1;
ret += curr >> 1;
if (curr == 1)
break;
}
return ret;
}
};