Implement int sqrt(int x).
Compute and return the square root of x.
Subscribe to see which companies asked this question
class Solution {
public:
int mySqrt(int x) {
int l = 1, r=x;
while(l <= r) {
int mid = (l+r)/2;
if(mid <= x/mid){
l = mid+1;
} else {
r = mid-1;
}
}
return l-1;
}
};
本文介绍了一种求解整数平方根的有效算法,并通过C++代码实现了该算法。使用二分查找法来逼近目标值,确保了计算的效率与准确性。
4664

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



