Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:
二分法。牛顿迭代法。
int mySqrt(int x) { if (x == 0) return 0; int left = 1, right = INT_MAX; while (1) { int mid = left + (right - left) / 2; if (mid * mid > x) { right = mid - 1; } else { if((mid + 1)*(mid+1) > x) { return mid; } left = mid + 1; } } }
int newton(int x) { if (x == 0) return 0; double ans = x; while (abs(pow(ans, 2) - x) > 0.001) { ans = (ans + x / ans) / 2; } return ans; }
参考:
https://discuss.leetcode.com/topic/8689/newton-s-iterative-method-in-c