367 Valid Perfect Square (Easy)
检验完全平方数
Given a positive integernum, write a function which returns True ifnumis a perfect square else False.
Note:Do notuse any built-in library function such assqrt
.
Example 1:
Input: 16
Returns: True
Example 2:
Input: 14
Returns: False
Solution:
A square number is 1+3+5+7+...
//The time complexity is O(sqrt(n))
public boolean isPerfectSquare(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
//The time complexity is O(log(n))
public boolean isPerfectSquare(int num) {
int low = 1, high = num;
while (low <= high) {
long mid = (low + high) >>> 1;
if (mid * mid == num) {
return true;
} else if (mid * mid < num) {
low = (int) mid + 1;
} else {
high = (int) mid - 1;
}
}
return false;
}