Leetcode No.69 Sqrt(x)开根号(c++实现)

时间:2021-08-16
本文章向大家介绍Leetcode No.69 Sqrt(x)开根号(c++实现),主要包括Leetcode No.69 Sqrt(x)开根号(c++实现)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 题目

https://leetcode.com/problems/sqrtx/

2. 分析

2.1 牛顿迭代法

牛顿迭代法是一种求解非线性方程的一种数值方法。具体原理可以参考: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

2.2 二分法

具体代码如下:

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

作者:云梦士
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/yunmeng-shi/p/15146461.html