Leetcode 69 Sqrt(x)

来源:互联网 发布:kk录制软件 编辑:程序博客网 时间:2024/06/03 20:59

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

class Solution {public:    int mySqrt(int x) {        int begin = 0;        int end = x;        // (begin + end) / 2 向左偏,所以end 可能未被检测        if (1 == x) return 1;        while (end - begin > 1) {            int mid = (begin + end) / 2;            if (mid == x / mid)                return mid;            else if (mid > x / mid)                end = mid;            else                 begin = mid;        }        return begin;    }};

参考后
牛顿法

class Solution {public:    int mySqrt(int x) {        long ret = x;        while (ret * ret > x) {            ret = (ret * ret + x) / (2 * ret);        }        return ret;    }};