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 Output: true
Example 2:
Input: 14 Output: false
解法:
要做到bug free,还是有点难度。二分法解决。
class Solution {
public boolean isPerfectSquare(int num) {
int left = 0; //起始要等于0
int right = num;
if(num <= 1)return true;
while(left <= right){ //大于等于
int mid = (left+right)/2;
if(mid*mid == num){
return true;
}
if(mid > num/mid){
right = mid-1; //减一
}else{
left = mid+1; //加一
}
}
return false;
}
}