Problem · String

Compare Version Numbers

Learn this problem
MediumInMobi logoInMobiFULLTIMEPHONE SCREEN

Problem 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 -1 when version1 is smaller.
  • Return 1 when version1 is larger.
  • Return 0 when the versions are equal.

Function

compareVersion(version1: String, version2: String) → int

Examples

Example 1

version1 = "1.2"version2 = "1.10"return = -1

The second revisions are 2 and 10, so the first version is smaller.

Example 2

version1 = "1.01"version2 = "1.001"return = 0

After leading zeroes are ignored, both second revisions equal 1.

Example 3

version1 = "1.0"version2 = "1.0.0.0"return = 0

The 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.

More InMobi problems

drafts saved locally
public int compareVersion(String version1, String version2) {
  // write your code here
}
version1"1.2"
version2"1.10"
expected-1
checking account