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
题目很简单,判断数能否被开平方
第一种,有点蠢的暴力枚举法:
public class Solution {
public boolean isPerfectSquare(int num) {
if(num==1||num==0){
return true;
}
for(int i=0;i<=num/2;i++){
if(i*i==num){
return true;
}
}
return false;
}
}
第二种,二分查找法
public class Solution {
public boolean isPerfectSquare(int num) {
long left = 0, right = num;
while (left <= right) {
long mid = left + (right - left) / 2, t = mid * mid;
if (t == num) return true;
else if (t < num) left = mid + 1;
else right = mid - 1;
}
return false;
}
}