-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompareVersionNumbers165.java
46 lines (42 loc) · 1.9 KB
/
CompareVersionNumbers165.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
public class CompareVersionNumbers165 {
/*
* Given two version numbers, version1 and version2, compare them.
*
* Version numbers consist of one or more revisions joined by a dot '.'.
* Each revision consists of digits and may contain leading zeros. Every revision contains at least one character.
* Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1,
* and so on. For example 2.5.33 and 0.1 are valid version numbers.
*
* To compare version numbers, compare their revisions in left-to-right order.
* Revisions are compared using their integer value ignoring any leading zeros.
* This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index,
* then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same,
* but their revision 1s are 0 and 1 respectively, and 0 < 1.
*
* Return the following:
*
* If version1 < version2, return -1.
* If version1 > version2, return 1.
* Otherwise, return 0.
*
*/
class Solution {
public int compareVersion(String v1, String v2) {
int n = v1.length() ;
int m = v2.length() ;
int i =0 , j =0 ;
while (i < n || j < m) {
int num1 = 0 ,num2 = 0;
while (i < n && v1.charAt(i) != '.')
num1 = num1*10 + v1.charAt(i++) ;
while (j < m && v2.charAt(j) != '.')
num2 = num2*10 + v2.charAt(j++) ;
if (num1 < num2) return -1;
else if (num2 < num1) return 1;
i++;
j++;
}
return 0 ;
}
}
}