165. Compare Version Numbers #107
-
|
Topics: Given two version numbers, Version numbers consist of one or more revisions joined by a dot To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions Return the following:
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We can use a two-pointer approach to traverse each version number and compare their segments.
Let's implement this solution in PHP: 165. Compare Version Numbers <?php
function compareVersion($version1, $version2) {
// Split the version numbers into arrays of segments
$v1 = explode('.', $version1);
$v2 = explode('.', $version2);
// Get the maximum length to iterate over both arrays
$length = max(count($v1), count($v2));
// Compare each segment
for ($i = 0; $i < $length; $i++) {
// Get the current segment from each version, defaulting to "0" if not present
$seg1 = isset($v1[$i]) ? (int)$v1[$i] : 0;
$seg2 = isset($v2[$i]) ? (int)$v2[$i] : 0;
// Compare segments
if ($seg1 < $seg2) {
return -1;
} elseif ($seg1 > $seg2) {
return 1;
}
}
// All segments are equal
return 0;
}
// Example usage
echo compareVersion("1.01", "1.001"); // Output: 0
echo compareVersion("1.0", "1.0.0"); // Output: 0
echo compareVersion("0.1", "1.1"); // Output: -1
?>Explanation:
This solution efficiently compares version numbers by considering each segment as an integer and handles cases where versions have different lengths by treating missing segments as |
Beta Was this translation helpful? Give feedback.
We can use a two-pointer approach to traverse each version number and compare their segments.
explodeto split each version number by the dot'.'character into arrays of segments.0.Let's implement this solution in PHP: 165. Compare Version Numbers