-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path367. Valid Perfect Square.cpp
More file actions
53 lines (41 loc) · 1.06 KB
/
367. Valid Perfect Square.cpp
File metadata and controls
53 lines (41 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//link: https://leetcode.com/problems/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.
Example 1:
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
Constraints:
1 <= num <= 2^31 - 1
*/
/*
Result:
Runtime: 4 ms, faster than 10.20% of C++ online submissions for Valid Perfect Square.
Memory Usage: 5.9 MB, less than 100.00% of C++ online submissions for Valid Perfect Square.
*/
class Solution {
public:
bool isPerfectSquare(int num) {
if(num == 1){
return true;
}
int high = num / 2;
int low = 1;
while(low <= high){
int mid = (high + low) / 2;
if(mid == num / mid && num % mid == 0){
return true;
}
else if(mid > num / mid){
high = mid - 1;
}
else{
low = mid + 1;
}
}
return false;
}
};