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
Related Topics:
Math, Binary Search
Similar Questions:
// OJ: https://leetcode.com/problems/valid-perfect-square/
// Author: github.com/lzl124631x
// Time: O(sqrt(num))
// Space: O(1)
class Solution {
public:
bool isPerfectSquare(int num) {
long i = 0;
while (i * i < num) ++i;
return i * i == num;
}
};
// OJ: https://leetcode.com/problems/valid-perfect-square/
// Author: github.com/lzl124631x
// Time: O(log(num))
// Space: O(1)
class Solution {
public:
bool isPerfectSquare(int num) {
long L = 1, R = num;
while (L <= R) {
long M = L + (R - L) / 2;
if (M * M == num) return true;
if (num / M < M) R = M - 1;
else L = M + 1;
}
return false;
}
};