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.
Subscribe to see which companies asked this question.
思路:二分查找。
public class Solution {
public boolean isPerfectSquare(int num) {
if (num == 1) {
return true;
}
int l, r, mid;
l = 1;
r = num / 2;
while (l <= r) {
mid = (l + r) / 2;
if (num % mid == 0 && num / mid == mid) {
return true;
} else if (num / mid < mid) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return false;
}
}