LeetCode69 Sqrt(x)**
链接地址:https://leetcode.com/problems/sqrtx/
这道题就是求一个数的平方根
我这里提供三种方法
1:大家都知道平方根一定都是[1,x/2]之间,所以从1循环到x/2, 但当x=1是通过的,不是好方法而且会TLE
class Solution { // TLE而且不精确
public:int sqrt(int x) {int t = x/2;for(int i = 0; i<= t; i++)if((i * i) == x) return i;return -1;}
};
2:二分法
我们知道二分法所需要的时间复杂度为O(lgN),这样就不会超时了
class Solution {
public:int sqrt(int x) {double begin = 0;double end = x;double result = 1;double mid = 1;while(abs(result-x) > 0.000001){mid = (begin+end)/2;result = mid*mid;if(result > x) // 二分的范围end = mid;else begin = mid;}return (int)mid;}
};
3:牛顿迭代法
牛顿迭代法(Newton's method)又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上近似求解方程的方法。
以下代码cur = pre/2 + x/(2*pre)是化简计算的结果。。这里的f(x) = x^2-n
//*牛顿迭代法*/
class Solution {
public:int sqrt(int x) {double pre = 0;double cur = x; // 这里从x开始 从x/2开始会导致 1 不能满足 x(n+1)= xn - f'(xn)/f(xn) while(abs(cur - pre) > 0.000001){pre = cur;cur = (pre/2 + x/(2*pre));}return int(cur);}
};
LeetCode69 Sqrt(x)**相关推荐
- LeetCode-69 Sqrt(x)
LeetCode-69 Sqrt(x) Implement int sqrt(int x). Compute and return the square root of x. 思路:二分法. 比较要留 ...
- Leetcode-69 Sqrt(x)
题目介绍 Implement int sqrt(int x). Compute and return the square root of x. 解决方法 int sqrt(int x) {if (0 ...
- [Java]Leetcode69 Sqrt(x)
Implement int sqrt(int x).Compute and return the square root of x. 题意:算一个数的平方根. 好不容易想到用二分查找来解决改题,但是也 ...
- [LeetCode-69]-Sqrt(根号运算)
文章目录 题目相关 Solution 1. 调用已有的库函数 题目相关 [题目解读] [原题描述]原题链接 Implement int sqrt(int x). Compute and return ...
- 17道题带你理解二分查找
不太会的可以先看看二分查找的模板 点这里 最需要注意的是二分查找的分界线并不止局限于大于等于小于,而是对某种性质的一种分界 1.Leetcode704. 二分查找 class Solution {pu ...
- Error in Math.factor() : ‘sqrt’ not meaningful for factors
Error in Math.factor() : 'sqrt' not meaningful for factors 目录 Error in Math.factor() : 'sqrt' not me ...
- R语言sqrt函数为数值开平方根实战
R语言sqrt函数为数值开平方根实战 目录 R语言sqrt函数为数值开平方根实战 #基本语法 #sqrt函数开平方根
- R语言数学函数:abs绝对值、sqrt平方根、ceiling向上近似整数、floor向下近似整数、trunc去除小数部分、round近似到指定小数位、signif近似到有效数字、三角函数、指数、对数
R语言数学函数:abs绝对值.sqrt平方根.ceiling向上近似整数.floor向下近似整数.trunc去除小数部分.round近似到指定小数位.signif近似到有效数字.三角函数.指数.对数 ...
- 湖南省第八届大学生程序设计大赛原题 D - 平方根大搜索 UVA 12505 - Searching in sqrt(n)...
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=30746#problem/D D - 平方根大搜索 UVA12505 - Searchin ...
- c语言sprt的程序怎么用,sqrt函数在c语言中怎么用?
c语言中,sqrt函数用于计算一个非负实数的平方根.使用方法:1.在程序中添加头文件"<math.h>":2.定义浮点类型变量x:3.使用sqrt(x)来求参数x的平方 ...
最新文章
- Unified Networking Lab 安装使用IOL镜像
- ubuntu 12.04及12.10无法安装 ia32-libs
- java 存储过程 数组参数_执行数组参数的存储过程
- perform指标分析_performace 监控统计
- visual studio 2015 配置好qt5后, 第一次运行出现 无法打开源文件“QtWidgets/QApplication”和无法运行rc.exe的解决方案
- SpringBoot使用@ServerEndpoint无法依赖注入问题解决 SpringBoot webSocket配置
- 新浪微盘等大批网盘将关停 你的私藏文件导出来了吗?
- python 连通区域检测_浅谈opencv自动光学检测、目标分割和检测(连通区域和findContours)...
- SSH系列:(26)投诉受理
- stm8 低功耗 RTC唤醒
- java中 是什么意思_java中?:是什么意思
- 我知我见:ftp共享
- 第九周项目六 委派任务
- Intel(R) WiFi Link 5100 AGN 破解无线网络 BT4正式版U盘启动
- 小工具推荐:tokei(高效统计代码行数)
- 不同手机类型该如何更换手机IP
- Trie 前缀树的c 实现
- 【转】在WPF显示动态GIF图片
- C#实现SqlServer连接查询
- Linux 之软连接