forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompare Version Numbers.java
More file actions
33 lines (32 loc) · 963 Bytes
/
Compare Version Numbers.java
File metadata and controls
33 lines (32 loc) · 963 Bytes
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
class Solution {
public int compareVersion(String version1, String version2) {
String[] versionOneSplit = version1.split("\\.");
String[] versionTwoSplit = version2.split("\\.");
int idxOne = 0;
int idxTwo = 0;
while (idxOne < versionOneSplit.length && idxTwo < versionTwoSplit.length) {
int diff = Integer.parseInt(versionOneSplit[idxOne]) - Integer.parseInt(versionTwoSplit[idxTwo]);
if (diff < 0) {
return -1;
} else if (diff > 0) {
return 1;
}
idxOne++;
idxTwo++;
}
if (containsNonZeroRevision(versionOneSplit, idxOne)) {
return 1;
} else if (containsNonZeroRevision(versionTwoSplit, idxTwo)) {
return -1;
}
return 0;
}
private boolean containsNonZeroRevision(String[] versions, int idx) {
for (int i = idx; i < versions.length; i++) {
if (Integer.parseInt(versions[i]) > 0) {
return true;
}
}
return false;
}
}