69. Sqrt(x)
来源:互联网 发布:js点击按钮旋转图片 编辑:程序博客网 时间:2024/06/17 19:47
Implement int sqrt(int x).
Compute and return the square root of x.
这道题要求我们求平方根,我们能想到的方法就是算一个候选值的平方,然后和x比较大小,为了缩短查找时间,我们采用二分搜索法来找平方根,由于求平方的结果会很大,可能会超过int的取值范围,所以我们都用long long来定义变量,这样就不会越界,代码如下:
解法一
// Binary Searchclass Solution {public: int sqrt(int x) { long long left = 0, right = (x / 2) + 1; while (left <= right) { long long mid = (left + right) / 2; long long sq = mid * mid; if (sq == x) return mid; else if (sq < x) left = mid + 1; else right = mid - 1; } return right; }};
这道题还有另一种解法,是利用牛顿迭代法,记得高数中好像讲到过这个方法,是用逼近法求方程根的神器,在这里也可以借用一下,可参见网友Annie Kim’s Blog的博客,因为要求x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,可以求出递推式如下:
xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2
解法二
// Newton's methodclass Solution {public: int sqrt(int x) { if (x == 0) return 0; double res = 1, pre = 0; while (res != pre) { pre = res; res = (res + x / res) / 2; } return int(res); }};
阅读全文
0 0
- LeetCode 69. Sqrt(x)
- LeetCode 69.Sqrt(x)
- LeetCode --- 69. Sqrt(x)
- [Leetcode] 69. Sqrt(x)
- [leetcode] 69.Sqrt(x)
- 69.Sqrt(x)
- 69. Sqrt(x)
- Leetcode-69.Sqrt(x)
- leetcode--69.sqrt(x)
- 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- 69. Sqrt(x)
- 69. Sqrt(x)
- [leetcode] 69. Sqrt(x)
- 69. Sqrt(x)
- Cells(Rows.Count, 1).End(xlUp).Row的含义
- 线程基础知识
- springboot学习笔记 -- Hello Word、返回json数据、fastJson、热部署
- 蝶式算法扩展-----16位按位转换
- 【noip2012】国王游戏
- 69. Sqrt(x)
- 机器学习之必知十大机器学习算法
- 幼儿园第四天
- 循环队列的实现
- RxPermissions的简单应用
- linux下编译安装zlib
- 应急指挥系统有什么内容
- shell 按行读取文件的问题
- Oil Deposits (八个方向搜索)