-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy path367. Valid Perfect Square.cpp
78 lines (68 loc) · 1.97 KB
/
367. Valid Perfect Square.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Perfect Square.
//Memory Usage: 8 MB, less than 83.44% of C++ online submissions for Valid Perfect Square.
class Solution {
public:
bool isPerfectSquare(int num) {
long long lnum = num;
for(long long i = 1; i * i <= lnum; i++){
if(i * i == lnum) return true;
}
return false;
}
};
//https://leetcode.com/problems/valid-perfect-square/discuss/83874/A-square-number-is-1%2B3%2B5%2B7%2B...-JAVA-code
/**
Approach 1 :A square number is 1+3+5+7+...
O(sqrt(n))
**/
//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Perfect Square.
//Memory Usage: 8 MB, less than 64.42% of C++ online submissions for Valid Perfect Square.
class Solution {
public:
bool isPerfectSquare(int num) {
int i = 1;
while(num > 0){
num -= i;
i += 2;
}
return num == 0;
}
};
/**
Approach 2 : binary search
O(logn)
**/
//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Perfect Square.
//Memory Usage: 8.1 MB, less than 55.21% of C++ online submissions for Valid Perfect Square.
class Solution {
public:
bool isPerfectSquare(int num) {
long long low = 1, high = num;
while(low <= high){
long long mid = (low+high) >> 1;
if(mid * mid == num){
return true;
}else if(mid * mid < num){
low = mid + 1;
}else{
high = mid - 1;
}
}
return false;
}
};
/**
Approach 3 : Newtown method
**/
/Runtime: 4 ms, faster than 100.00% of C++ online submissions for Valid Perfect Square.
//Memory Usage: 8.1 MB, less than 50.92% of C++ online submissions for Valid Perfect Square.
class Solution {
public:
bool isPerfectSquare(int num) {
long long x = num;
while(x * x > num){
x = (x + num/x) >> 1;
}
return x*x == num;
}
};