(x0 越接近S的平方根越好)
class Solution { public: int sqrt(double x) { if(x == 0) return 0; double root = x/2, tolerance = 1.0e-2; do{ root=(root+x/root)/2; }while(abs(root*root-x)>tolerance); return root; } };
这题感觉题目有问题,返回的平方根竟然是整数,
另一种方法是是用二分搜索
class Solution { public: int sqrt(int x) { if(x < 2) return x; int left = 0, right = x; while(left <= right){ int mid = (right+left)/2; if(mid < x/mid) left = mid+1; else if(x/mid < mid ) right = mid-1; else return mid; } return right; } };
如果题目要求的时浮点数可以考虑利用浮点数二分搜索