题目:
解法一:
因为是返回的int值 所以可以用二分法,注意数据类型用unsingned long long 而不是int
如果没有找到合适的值 返回end 或者是end-1
class Solution {
public:
int sqrt(int x) {
int begin = 0;
int end = (x + 1) / 2;
int mid;
while (begin < end)
{
mid = begin + (end - begin) / 2;
if (mid*mid == x)
return mid;
else if (mid*mid < x)
begin = mid + 1;
else
end = mid - 1;
}
if (end*end > x)
return end - 1;
return end;
}
};
解法二:
牛顿迭代法:
参见;http://blog.csdn.net/doc_sgl/article/details/12404971