-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day-09-validPerfectSquare.java
57 lines (52 loc) · 1.47 KB
/
Day-09-validPerfectSquare.java
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
/*
class Solution {
//Approach1 - fails when num = 2147483647
public boolean isPerfectSquare(int num) {
for (int s=0,i=1;s<num;i+=2){
s+=i;
if(s==num)
return true;
}
return false;
}
//Approach2 - fails when num = 2147483647
public boolean isPerfectSquare(int num) {
for (int i=1;i*i<=num;i+=1){
if((num%i==0)&&(num/i==i)) //if(i*i==num)
return true;
}
return false;
}
//Approach3 - fails when num = 2147483647
public boolean isPerfectSquare(int num) {
for (int i=1;i*i<=num;i+=1){
if(i*i==num)
return true;
}
return false;
}
//Approach4 - runtime on leetcode is 0ms
public boolean isPerfectSquare(int num) {
long a = num;
while(a*a>num)
a=(a+num/a)/2;
return a*a==num;
}
}
*/
class Solution {
//Approach5 - BinarySearch Approach - runtime on leetcode is 0ms
public boolean isPerfectSquare(int num) {
long left = 1,right = (long)Integer.MAX_VALUE,mid,sqrMid;
while (left <= right){
mid = (left + right) / 2;
sqrMid = mid * mid;
if (sqrMid == num)
return true;
else if (sqrMid > num)
right = mid - 1;
else left = mid + 1;
}
return false;
}
}