Skip to content

165. Compare Version Numbers 👎

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int compareVersion(string version1, string version2) {
    istringstream iss1(version1);
    istringstream iss2(version2);
    int v1;
    int v2;
    char dotChar;

    while (bool(iss1 >> v1) + bool(iss2 >> v2)) {
      if (v1 < v2)
        return -1;
      if (v1 > v2)
        return 1;
      iss1 >> dotChar;
      iss2 >> dotChar;
      v1 = 0;
      v2 = 0;
    }

    return 0;
  };
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int compareVersion(String version1, String version2) {
    final String[] levels1 = version1.split("\\.");
    final String[] levels2 = version2.split("\\.");
    final int length = Math.max(levels1.length, levels2.length);

    for (int i = 0; i < length; ++i) {
      final Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
      final Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
      final int compare = v1.compareTo(v2);
      if (compare != 0)
        return compare;
    }

    return 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def compareVersion(self, version1: str, version2: str) -> int:
    levels1 = version1.split('.')
    levels2 = version2.split('.')
    length = max(len(levels1), len(levels2))

    for i in range(length):
      v1 = int(levels1[i]) if i < len(levels1) else 0
      v2 = int(levels2[i]) if i < len(levels2) else 0
      if v1 < v2:
        return -1
      if v1 > v2:
        return 1

    return 0