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||x==1) return x;
int start,end;
long long mid; //!!!!!!int may cause overflow
start=1,end=x>>1;
while(end>=start){
mid=(start+end)>>1;
if(mid*mid<=x && (mid+1)*(mid+1)>x)
return mid;
else if(mid*mid>x)
end=mid-1;
else
start=mid+1;
}//while
}
};

本文介绍了一种使用C++来计算整数平方根的方法。该算法通过二分查找的方式找到最接近输入值平方根的最大整数,并妥善处理了边界情况如输入为0或1的情况。同时,为避免整数溢出的问题,将中间值类型设置为long long。
302

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



