(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; } };
如果題目要求的時浮點數可以考慮利用浮點數二分搜尋