【LeetCode】Sqrt(x)
来源:互联网 发布:逃犯 熊孩子 知乎 编辑:程序博客网 时间:2024/06/06 20:50
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:从[1,x/2]中利用二分法查找结果。
可取小不可取大(如8只能返回2,不能返回3),故在增加left的时候,要保存当前的中间值。
为了避免溢出,使用x/mid > mid,而不用x > mid*mid;
class Solution {public: int sqrt(int x) { if(x < 2)return x; int left = 1; int right = x / 2; int lastmid; while(left <= right) { int mid = left + (right - left)/2; if(x / mid > mid) { left = mid + 1; lastmid = mid; } else if (x / mid < mid) { right = mid -1; } else return mid; } return lastmid; }};
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)
- python+selenium安装配置教程
- nyoj-409 郁闷的C小加(三) (表达式求值,中缀式转前缀式,中缀式转后缀式)
- 在 Eclipse Galileo 中更快地编写 Java 代码
- Mysql更新语句中的safe_mode
- 汉字拼音首字母 简繁体等转换
- 【LeetCode】Sqrt(x)
- IOS7.1 企业应用 证书无效 已解决
- 删除包时,报ORA-04043: object SYS_PLSQL×× dose not exists
- wait函数和waitpid函数比较
- Oracle数据库SqlLoad常用技巧总结(转载)
- 黑马程序员_JAVA动态代理技术学习笔记
- matlab 读取excel 数据
- 初学opencv心得:imshow中断退出问题和stitcher报错问题
- X86_X64