https://leetcode.com/problems/sqrtx/
牛顿迭代法是一种求解非线性方程的一种数值方法。具体原理可以参考:https://blog.csdn.net/u014485485/article/details/77599953
具体代码如下:
class Solution { public: int mySqrt(int x) { if (x == 0) { return 0; } int r = x; while (r > x / r) { r = x / r + (r - x/ r) / 2; } return r; } };
代码参考:https://leetcode.com/problems/sqrtx/discuss/25057/3-4-short-lines-Integer-Newton-Every-Language
具体代码如下:
class Solution { public: int mySqrt(int x) { if (x == 0 || x == 1) { return x; } int left = 0; int right = x; while (left <= right) { int mid = left + (right - left) / 2; if (mid <= x / mid) { left = mid + 1; } else { right = mid - 1; } } return right; } };
代码参考:https://leetcode.com/problems/sqrtx/discuss/25047/A-Binary-Search-Solution