【LeetCode】69. Sqrt(x) (2 solutions)
Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
解法一:牛顿迭代法
求n的平方根,即求f(x)=x2-n的零点
设初始值为x0,注,不要设为0,以免出现除数为0,见后。
则过(x0,f(x0))点的切线为g(x)=f(x0)+f'(x0)*(x-x0)
g(x)与x轴的交点为x1=x0-f(x0)/f'(x0)
递推关系为xn+1=xn-f(xn)/f'(xn)
当收敛时即为解。
class Solution { public:int sqrt(int x) {double x0 = 1;double x_next = -(x0*x0 - x)/(2*x0) + x0;while(fabs(x0-x_next) > 0.00001){x0 = x_next;x_next = -(x0*x0 - x)/(2*x0) + x0;}return x0;} };
解法二:二分法
注意返回为int,结果会取整。
class Solution { public:int sqrt(int x) {long long low = 0;long long high = x;long long mid;while(low <= high){mid = (low+high)/2;long long result = mid*mid;if(result == x)return mid;else if(result > x)high = mid-1;elselow = mid+1;}return high;} };
转载于:https://www.cnblogs.com/ganganloveu/p/4153935.html
【LeetCode】69. Sqrt(x) (2 solutions)相关推荐
- 【LeetCode】44. Wildcard Matching (2 solutions)
Wildcard Matching Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any ...
- 【LeetCode】48. Rotate Image (2 solutions)
Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees ...
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...
- 【LeetCode】【HOT】739. 每日温度(栈)
[LeetCode][HOT]739. 每日温度 文章目录 [LeetCode][HOT]739. 每日温度 package hot;import java.util.ArrayDeque; impo ...
- 【LeetCode】剑指 Offer 57 - II. 和为s的连续正数序列
[LeetCode]剑指 Offer 57 - II. 和为s的连续正数序列 文章目录 [LeetCode]剑指 Offer 57 - II. 和为s的连续正数序列 一.求和公式 二.滑动窗口(双指针 ...
- 【leetcode】963. Minimum Area Rectangle II
题目如下: Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from ...
- 【LEETCODE】【史密斯数】
[LEETCODE][史密斯数] 题目描述 Simth数的概念:一个非素数,其各位之和等于其所有质因数的各位之和.例如: 4=2 2,4=2+2,所以4是一个史密斯数. 22=211,2+2=2+1+ ...
- 【LeetCode】动态规划入门(专项打卡21天合集)
[LeetCode]动态规划入门(专项打卡21天合集) 下图为证 文章目录 [LeetCode]动态规划入门(专项打卡21天合集) Day1 斐波拉契数 第 N 个泰波那契数 Day2 爬楼梯 使用最 ...
- 【LeetCode】1631. Path With Minimum Effort 最小体力消耗路径(Medium)(JAVA)每日一题
[LeetCode]1631. Path With Minimum Effort 最小体力消耗路径(Medium)(JAVA) 题目描述: You are a hiker preparing for ...
最新文章
- 《代码敲不队》第八次团队作业:Alpha冲刺 第二天
- js中判断两个数字的大小
- JS 全局对象 全局变量 作用域 (改自TOM大叔博文)
- 指向字符串的指针为何不能用来修改此字符串
- 前沿分享|阿里云数据库资深技术专家 姚奕玮:AnalyticDB MySQL离在线一体化技术揭秘
- linux字符设备移动硬盘,Red Hat Enterprise Linux 7.5挂载NTFS移动硬盘
- [Java]Thinking in Java 练习2.2
- Vue指令_常用vue指令_自定义全局指令_自定义局部指令---vue工作笔记0016
- 该行已经属于另一个表 的解决方法
- 泛微 linux mobile手册,泛微E-Mobile5.0服务端安装手册.doc
- 台式计算机设置热点,台式电脑怎样设置wifi热点?设置wifi热点流程一览
- win10 更新计算机时间,win10电脑时间不能自动更新
- 备份服务器虚拟机,虚拟机备份与复制的区别
- 显微镜C接口_壁虎支架、AI相机、手机镜头、便携显微镜,十一旅行有它们更精彩...
- matlab 回归分析t检验,第三章 利用Matlab和SPSS进行线性回归分析
- 阿里云字体图标的引用
- 一首歌一个故事 -- 忘记你我做不到
- iOS开发,导入c文件引发的 Unknown type name 'NSString' 问题
- 网络安全入门教程(非常详细),从零基础入门到精通,看完这一篇就够了
- python实现典型相关分析_R语言典型相关分析