[LeetCode] Valid Perfect Square

367. Valid Perfect Square

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Follow up: Do not use any built-in library function such as sqrt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isPerfectSquare(int num) {
long long l = 1, r = INT_MAX;
while(l <= r) {
long long m = l + (r - l) / 2;
long long product = m * m;
if(product == num) return true;
else if(product < num) l = m + 1;
else r = m - 1;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/valid-perfect-square/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.