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
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
思路1:Binary Search, Accepted.
class Solution {
public boolean isPerfectSquare(int num) {
if(num < 0) throw new IllegalArgumentException("num must be positive");
int start = 0; int end = num;
while(start<=end){
int mid = start+(end-start)/2;
if(Math.pow(mid,2) == num){
return true;
} else if(Math.pow(mid,2) > num){
end = mid-1;
} else { // Math.pow(mid,2) < num;
start = mid+1;
}
}
return false;
}
}
思路2:一种收缩上限的方法,那就是num/i,搜索1到sqrt(num)的上线,这里并没有用sqrt,而是用了除法。很巧妙。
i<=num/i, 实际上i的取值范围是1~ sqrt(num);
class Solution {
public boolean isPerfectSquare(int num) {
if(num < 0) throw new IllegalArgumentException("Num must be positive");
if(num == 0 || num == 1) return true;
for(int i=1; i<=num/i; i++){
if( i*i == num){
return true;
}
}
return false;
}
}