[Leetcode] Sqrt(x)

Implement int sqrt(int x).

Compute and return the square root of x.

牛顿迭代法, 碉堡了。

class Solution {

public:

    int sqrt(int x) {

        double ans = x;

        while (abs(ans * ans - x) > 0.0001) {

            ans = (ans + x / ans) / 2;

        }

        return (int)ans;

    }

};

 

你可能感兴趣的:(LeetCode)