Sqrt(x) -- leetcode
来源:互联网 发布:g代码编程实例图片 编辑:程序博客网 时间:2024/06/07 02:28
Implement int sqrt(int x)
.
Compute and return the square root of x.
此代码在leetcode上实际执行时间为16ms。
基本思路为二分法。
由于二段式二分法,退出循环时,有两种情况,一是精确匹配,二是精确值不存在情况下,指向稍大一点的。故函数返回时需要判断一下。
另外一点需要注意的是,作判断时,不能用 mid * mid < x, 而是要写成 mid < x / mid。 因为剩法会溢出,而除法不会溢出。
class Solution {public: int sqrt(int x) { if (!x) return x; int l = 1, h = x; while (l < h) { const int mid = l + (h - l) / 2; if (mid < x / mid) l = mid + 1; else h = mid; } return l == x / l ? l : l - 1; }};
0 0
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 【leetcode】sqrt(int x)
- [LeetCode]Sqrt(x)
- [leetcode]Sqrt(x)
- LeetCode-Sqrt(x)
- [leetcode] Sqrt(x)
- [leetcode] Sqrt(x)
- LeetCode - Sqrt(x)
- leetcode之sqrt(x)
- LeetCode | Sqrt(x)
- COL命令详解
- Java包命名规则引发的思考
- ubuntu 配置 pptpd关键项目
- ajax跨域调用
- 数组 4Sum
- Sqrt(x) -- leetcode
- linux常见服务端口
- 报文交换数据小练习
- 神秘顾客观质量控制要点
- 注解框架---AndroidAnnotations
- Android FragmentManage FragmentTransaction介绍
- SharePoint 2010自定义母版页小技巧——JavaScript和CSS引用
- 游戏机制新设计工具(Machinations)工作原理
- java中对象的引用(强引用、软引用、弱引用、虚引用)