Implement int sqrt(int x).
Compute and return the square root of x.
class Solution {
public:
//二分查找
int sqrt(int x) {
long long left = 0, right = x;
while (left <= right) {
long long mid = (left + right) / 2;
if (mid*mid == x)
return mid;
else if (mid*mid < x)
left = mid + 1;
else
right = mid - 1;
}
return right;
}
};
本文介绍了一种使用二分查找算法来计算整数平方根的方法。通过不断缩小搜索范围,该算法能够高效准确地找到指定整数的平方根。
186

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



