防止溢出 LeetCode69.Sqrt(x)

题目描述:

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)

 

posted @ 2018-04-01 10:33  起点菜鸟  阅读(146)  评论(0)    收藏  举报