Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt
.
Example 1:
Input: 16 Returns: True
Example 2:
Input: 14 Returns: False
这道题的思路是二分,但是需要注意越界的问题。二分查找的上下界是0~ math.sqrt(Intger.Max_value)+1,因为比他大了之后平方数就越界了就不需要考虑了。
代码:
public boolean isPerfectSquare(int num) {
//如果不用的话,那么可能在一些数之后会溢出。
long low =0;
long high = (long)Math.sqrt(Integer.MAX_VALUE)+1L;
while (low <= high) {
long mid = low + (high - low)/2;
if(mid * mid == num)
return true;
if(mid * mid < num){
low = mid +1;
}else{
high = mid - 1;
}
}
return false;
}