|
| 1 | +Compare two version numbers version1 and version2. |
| 2 | +If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0. |
| 3 | + |
| 4 | +You may assume that the version strings are non-empty and contain only digits and the . character. |
| 5 | + |
| 6 | +The . character does not represent a decimal point and is used to separate number sequences. |
| 7 | + |
| 8 | +For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. |
| 9 | + |
| 10 | +You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0. |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +Example 1: |
| 15 | + |
| 16 | +Input: version1 = "0.1", version2 = "1.1" |
| 17 | +Output: -1 |
| 18 | +Example 2: |
| 19 | + |
| 20 | +Input: version1 = "1.0.1", version2 = "1" |
| 21 | +Output: 1 |
| 22 | +Example 3: |
| 23 | + |
| 24 | +Input: version1 = "7.5.2.4", version2 = "7.5.3" |
| 25 | +Output: -1 |
| 26 | +Example 4: |
| 27 | + |
| 28 | +Input: version1 = "1.01", version2 = "1.001" |
| 29 | +Output: 0 |
| 30 | +Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1” |
| 31 | +Example 5: |
| 32 | +
|
| 33 | +Input: version1 = "1.0", version2 = "1.0.0" |
| 34 | +Output: 0 |
| 35 | +Explanation: The first version number does not have a third level revision number, which means its third level revision number is default to "0" |
| 36 | +
|
| 37 | +
|
| 38 | +Note: |
| 39 | +
|
| 40 | +Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes. |
| 41 | +Version strings do not start or end with dots, and they will not be two consecutive dots. |
| 42 | +
|
| 43 | +
|
| 44 | +
|
| 45 | +
|
| 46 | +
|
| 47 | +
|
| 48 | +
|
| 49 | +
|
| 50 | +class Solution { |
| 51 | +public: |
| 52 | + int compareVersion(string version1, string version2) { |
| 53 | + int n1=version1.length(); |
| 54 | + int n2=version2.length(); |
| 55 | +
|
| 56 | + int num1=0, num2=0; |
| 57 | + int i=0, j=0; |
| 58 | + while(i<n1 || j<n2){ |
| 59 | + while(i< n1 && version1[i]!='.'){ |
| 60 | + num1=(num1*10)+(version1[i]-'0'); |
| 61 | + i++; |
| 62 | + } |
| 63 | + while(j<n2 && version2[j]!='.'){ |
| 64 | + num2=(num2*10)+(version2[j]-'0'); |
| 65 | + j++; |
| 66 | + } |
| 67 | +
|
| 68 | + if(num1>num2) return 1; |
| 69 | + if(num1<num2) return -1; |
| 70 | +
|
| 71 | + num1=0; |
| 72 | + num2=0; |
| 73 | +
|
| 74 | + i++; |
| 75 | + j++; |
| 76 | + } |
| 77 | + return 0; |
| 78 | + } |
| 79 | +}; |
0 commit comments