第十五周:69. Sqrt(x)
来源:互联网 发布:mac 装双系统 怎么备份 编辑:程序博客网 时间:2024/05/29 17:37
Implement int sqrt(int x)
.
Compute and return the square root of x.
X的平方根肯定会比X小,因此在1~X的范围内用二分查找的方法找到这个数。一开始的时候出现超时,超时代码如下:
int mySqrt(int x) { int mid; int low=0; int high=x; while(high>=low) { mid=(high+low)/2; if(x>mid*mid) low=mid+1; else if(x<mid*mid) high=mid-1; else return mid; } return high;}
我怎么想都解决不了这个问题,知道我将mid定义成Long型,就这样解决问题,这样可以防止mid*mid越界。
AC:
int mySqrt(int x) { long mid; int low=0; int high=x; while(high>=low) { mid=(high+low)/2; if(x>mid*mid) low=mid+1; else if(x<mid*mid) high=mid-1; else return mid; } return high;}
0 0
- 第十五周: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)
- 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)
- TypeScript设计模式之门面、适配器
- easyui tree 递归查询树 oracle为例
- OpenCV 与 SVM
- Android高德地图使用之地点关键词的输入提示-InputTips
- 字符串排序
- 第十五周:69. Sqrt(x)
- Java面向对象思想
- 网易编程题(2)
- Vim简明教程
- 执行docker ps命令,出现 "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. ..."问题
- BZOJ P1084[scoi2005]最大子矩阵
- HTTP协议的报文结构
- HashTable
- 设计模式---命令模式(C++实现)