Implement int sqrt(int x).
Compute and return the square root of x.
[解题方法]
二分法,注意溢出的处理方法
[代码]
class Solution {
public:
int sqrt(int x) {
if (x < 0) return -1;
if (x == 0) return 0;
if (x <= 3) return 1;
int left = 1;
int right = x / 2 + 1;
while (left <= right) {
int mid = (left + right) / 2;
if (mid <= x / mid && (mid + 1) > x / (mid + 1)) {
return mid;
} else if (mid > x / mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
};
本文介绍了一种使用二分法高效计算整数平方根的方法,并提供了一个C++实现示例。该方法适用于非负整数输入,通过不断缩小搜索范围直至找到最接近平方根的整数值。
186

被折叠的 条评论
为什么被折叠?



