首页 > 其他 > 详细

防止溢出 LeetCode69.Sqrt(x)

时间:2018-04-01 11:37:02      阅读:264      评论:0      收藏:0      [点我收藏+]

题目描述:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

思路:二分查找,时间复杂度O(logn)。

if(mid的平方等于x或者mid的平方小于x且mid+1的平方大于x) return mid;

可能溢出的地方:

1、(left+right)/2 因为(left+right)可能大于Integer.MAX_VALUE。

解决方案:(left+right)/2 ==> left + (right-left)/2;

2、mid*mid    (mid+1)*(mid+1)

解决:if(mid*mid==x)  ==> if(mid==x/mid)

 

防止溢出 LeetCode69.Sqrt(x)

原文:https://www.cnblogs.com/rookielet/p/8685882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!