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

posted @   云梦士  阅读(250)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示