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
Solution1:Math
思路:A square number is 1+3+5+7+...
Time Complexity: O(sqrt(n)) Space Complexity: O(1)
Solution2:Binary Search
Time Complexity: O(log(n)) Space Complexity: O(1)
Solution3:Newton Methold
reference: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
Time Complexity: O(log(n)) Space Complexity: O(1)
Solution1 Code:
class Solution1 {
public boolean isPerfectSquare(int num) {
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
}
}
Solution2 Code:
class Solution {
public boolean isPerfectSquare(int num) {
int start = 1, end = num;
while(start <= end) {
int mid = start + (end - start) / 2;
if (num / mid == mid && num % mid == 0) { //becuase mid * mid will overflow
return true;
} else if (num / mid > mid) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return false;
}
}
Solution3 Code:
class Solution {
public boolean isPerfectSquare(int num) {
long x = num;
while (x * x > num) {
x = (x + num / x) >> 1;
}
return x * x == num;
}
}