69-Sqrt(x)
来源:互联网 发布:windows git 环境变量 编辑:程序博客网 时间:2024/06/05 08:30
题目
Implement int sqrt(int x).
Compute and return the square root of x.
分析
这个题里面是有许多陷阱的
- 首先确定用二分法处理这个问题
- 然而0-x之间的num的平方有可能会溢出,所以不要使用num*num,如果使用的话要用long long 存储
- 还有left 不能为0,如果mid 也为零的话,x/mid 就会出错误
- 最后一个比较坑的是近似的问题,见注释。
实现
/*//Author:fancyDate : 2017-03-14Algrithm : 69-Sqrt(x)Time Complexity: 0(lg(n))Method: Binary Search*/class Solution {public: int mySqrt(int x) { if (x <= 1) return x; int left = 1; int right = x; while (left < right) { int mid = left + (right - left) / 2; if (mid == x / mid) return mid; else if (mid < x / mid) { //比如求sqrt(2) //1的平方为1,2的平方为4,所以sqrt(2)的结果在1和2 之间 //输出结果应该是1,但如果不加判断的话,就会跳过1,left赋值为2,继续操作。 if(mid+1>x/(mid+1)) return mid; left = mid+1; } else right = mid - 1; } return right; }};
阅读全文
0 0
- Leetcode 69 sqrt(x)
- leetcode 69 Sqrt(x)
- [leetcode 69] Sqrt(x)
- [leetcode] 69 Sqrt(x)
- leetcode-69 Sqrt(x)
- LeetCode 69 Sqrt(x)
- leetcode || 69、Sqrt(x)
- LeetCode 69 Sqrt(x)
- LeetCode-69 Sqrt(x)
- 69 Sqrt(x)
- Sqrt(x) - LeetCode 69
- leetcode 69:Sqrt(x)
- LeetCode---(69)Sqrt(x)
- Leetcode #69 Sqrt(x)
- LeetCode(69) Sqrt(x)
- leetcode 69: Sqrt(x)
- Leetcode#69||Sqrt(x)
- [Leetcode]#69 Sqrt(x)
- 显示背景隐藏文本 使用text-indent:-99999px 遇到的一些
- 2016 年 Java 优秀文章
- 深入理解Java异常处理机制
- 数学优化与凸集2(斯坦福凸优化笔记2)
- MulVAL 工具安装配置
- 69-Sqrt(x)
- js时间差
- Android 6.0系统读写文件出现FileNotFoundException:EACCES (permission denied)解决办法
- Android中一些开发的小技巧总结(持续更新)
- 获取Web.config中链接字符串和获取配置文件的Key和静态类中获取session
- 70-Climbing Stairs
- 深浅拷贝
- EL-------6.23
- Linux ALSA声卡驱动之一:ALSA架构简介