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
Approach #1:
class Solution { public: bool isPerfectSquare(int num) { long long l = 0, r = num; while (l <= r) { long long m = l + (r - l) / 2; long long flag = m * m; if (flag == num) return true; if (flag < num) l = m + 1; if (flag > num) r = m - 1; } return false; } };
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Valid Perfect Square.