Compare Version Numbers
MediumString · Adobe
You are given two version strings a and b. A version string is one or more revisions separated by dots, such as "2.10.0". Each revision is a non-negative integer and may contain leading zeros.
Compare the versions revision by revision, from left to right:
- Compare revisions by their integer value, so leading zeros are ignored (
"01"equals"1") and"10"is greater than"9". - If one version has fewer revisions, treat its missing revisions as
0(so"1.2"equals"1.2.0.0"). - The first revision that differs decides the result.
Return 1 if a is greater than b, -1 if a is less than b, and 0 if they are equal.
Example 1
- Input:
- a = "2.10", b = "2.9"
- Output:
- 1
- Explanation
- The first revisions are both 2. In the second, 10 is greater than 9 as integers (even though
"10"would sort before"9"as text), soais greater.
Example 2
- Input:
- a = "1.2", b = "1.2.0.1"
- Output:
- -1
- Explanation
ais treated as 1.2.0.0. The fourth revision is 0 versus 1, soais smaller.
Example 3
- Input:
- a = "3.00.010", b = "3.0.10"
- Output:
- 0
- Explanation
- Ignoring leading zeros, both are 3.0.10, so they are equal.
Constraints
- 1 ≤
a.length,b.length≤ 500 aandbcontain only digits and.- Neither string starts or ends with
., and there are no consecutive dots - Every revision fits in a 32-bit signed integer