September LeetCoding Challenge, Day 9: Compare Version Numbers
September 13, 2020The problem for September 9 is Compare Version Numbers. Given two
version numbers version1
and version2
, represented as strings, you want to
return -1 if version1
is smaller than version2
, 1 if version1
is larger
than version2
, and 0 if they’re equal. Versions are strings consisting of one
or more revisions joined by a .
. Each revision consists of digits only, but
may contain leading zeros. Every revision contains at least one character, so
it’s impossible for a substring of two .
to exist. Comparing versions consists
in comparing the integer value of its revisions in left-to-right order. If a
version doesn’t specify a revision at a given index, then the revision should be
treated as 0.
A solution for this problem consists in splitting the two provided strings in two sequences of numbers and do a pairwise comparison of them. Whenever a version number is missing a revision, assume 0 as its value. The following is an implementation of this strategy: