【Leetcode】69. Sqrt(x) 【溢出?如何防止?】
来源:互联网 发布:投资网络 编辑:程序博客网 时间:2024/06/05 06:40
69.Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
代码:
class Solution {
public:
int mySqrt(int x) {
if(x<2)
return x;
int lef=0,rig=x;
int mid=0;
while(rig>lef+1) { mid=(rig+lef)/2; if( x/mid < mid ) { rig=mid; } else { lef=mid; } } return lef;}
};
一开始我写的是这么个判断条件
if(x < mid*mid)
这里并没有注意到mid*mid会溢出!!!,溢出之后取模后又变成很小的,于是LeetCode提示Time Limit
怎么办?
也许你注意到了,改成这么个样子就不会溢出
if(x/mid < mid)
当然也有黑科技将INT_MAX开根号的值作为上限。
对于数字加减乘除一定要警惕溢出,要建立意识啊!
阅读全文
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)
- leetcode 69. Sqrt(x)
- 【LeetCode】69. Sqrt(x)
- 69. Sqrt(x) LeetCode
- [leetcode] 69. Sqrt(x)
- leetcode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- LeetCode 69. Sqrt(x)
- leetcode-69. Sqrt(x)
- [leetcode]69. Sqrt(x)
- gdb调试
- python 3 django连接mysql数据库配置
- uva 1585 Score
- Java程序员转战C++项目 之 如何上传本地源代码到Github
- JVM 内存分代、垃圾回收漫谈
- 【Leetcode】69. Sqrt(x) 【溢出?如何防止?】
- mysql commit和rollback
- Linux shell脚本变量单引号和双引号的区别以及变量扩展问题
- POJ
- 算法之二分查找(java版实现加测试)
- 线程管理
- 集合相关问题整理
- ios 分类(category)和类扩展(extension)详解
- Cesium学习笔记(七):Demo学习(自由控制飞行的飞机)