Problem · String
Compare Version Numbers
Learn this problemProblem statement
Given two version strings version1 and version2, compare them.
A version consists of revisions separated by dots. Convert each revision to an integer, ignoring leading zeroes, and compare revisions from left to right. If one version has fewer revisions, treat each missing revision as 0.
- Return
-1whenversion1is smaller. - Return
1whenversion1is larger. - Return
0when the versions are equal.
Function
compareVersion(version1: String, version2: String) → intExamples
Example 1
version1 = "1.2"version2 = "1.10"return = -1The second revisions are 2 and 10, so the first version is smaller.
Example 2
version1 = "1.01"version2 = "1.001"return = 0After leading zeroes are ignored, both second revisions equal 1.
Example 3
version1 = "1.0"version2 = "1.0.0.0"return = 0The missing revisions in the first version are treated as 0, so the versions are equal.
Constraints
1 ≤ version1.length, version2.length ≤ 500- Both strings are valid version numbers containing only digits and dots.
- Every revision fits in a signed 32-bit integer.