Compare Version Numbers

Medium~15 min

Given two version strings version1 and version2, compare them.

Version strings consist of one or more numeric parts separated by dots '.'. Each part is a non-negative integer.

Compare the parts left to right. If one version has fewer parts, treat the missing parts as 0.

Return:

  • -1 if version1 < version2
  • 1 if version1 > version2
  • 0 if they are equal

For example, "1.0" and "1" are equal because the missing part in "1" is treated as 0.

Examples

Example 1
Input: version1 = "1.2.3", version2 = "1.2.4"
Output: -1
Explanation: At the third part, 3 < 4, so version1 is less than version2.
Example 2
Input: version1 = "1.0", version2 = "1"
Output: 0
Explanation: version2 has no second part, which is treated as 0. "1.0" == "1.0".
Example 3
Input: version1 = "2.0.1", version2 = "2.0.0"
Output: 1
Explanation: At the third part, 1 > 0, so version1 is greater.

Constraints

  • 1 <= version1.length, version2.length <= 100
  • Version strings consist of digits and dots only.
  • Each numeric part is a valid non-negative integer (no leading zeros issues for comparison — treat as integers).
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run