Compare Version Numbers
Problem
Compare two version strings of the form X.Y.Z.... For each dot-separated chunk, compare the integers; missing chunks are treated as 0. Return 1 if version1 > version2, -1 if version1 < version2, else 0.
version1 = "1.2", version2 = "1.10"-1def compare_version(v1, v2):
i = j = 0
while i < len(v1) or j < len(v2):
a = 0
while i < len(v1) and v1[i] != ".":
a = a * 10 + int(v1[i])
i += 1
b = 0
while j < len(v2) and v2[j] != ".":
b = b * 10 + int(v2[j])
j += 1
if a < b:
return -1
if a > b:
return 1
i += 1
j += 1
return 0
function compareVersion(v1, v2) {
let i = 0, j = 0;
while (i < v1.length || j < v2.length) {
let a = 0;
while (i < v1.length && v1[i] !== ".") { a = a * 10 + (v1.charCodeAt(i) - 48); i++; }
let b = 0;
while (j < v2.length && v2[j] !== ".") { b = b * 10 + (v2.charCodeAt(j) - 48); j++; }
if (a < b) return -1;
if (a > b) return 1;
i++; j++;
}
return 0;
}
class Solution {
public int compareVersion(String v1, String v2) {
int i = 0, j = 0;
while (i < v1.length() || j < v2.length()) {
int a = 0;
while (i < v1.length() && v1.charAt(i) != '.') { a = a * 10 + (v1.charAt(i) - '0'); i++; }
int b = 0;
while (j < v2.length() && v2.charAt(j) != '.') { b = b * 10 + (v2.charAt(j) - '0'); j++; }
if (a < b) return -1;
if (a > b) return 1;
i++; j++;
}
return 0;
}
}
int compareVersion(string v1, string v2) {
int i = 0, j = 0;
while (i < (int) v1.size() || j < (int) v2.size()) {
int a = 0;
while (i < (int) v1.size() && v1[i] != '.') { a = a * 10 + (v1[i] - '0'); i++; }
int b = 0;
while (j < (int) v2.size() && v2[j] != '.') { b = b * 10 + (v2[j] - '0'); j++; }
if (a < b) return -1;
if (a > b) return 1;
i++; j++;
}
return 0;
}
Explanation
Version strings like 1.2 and 1.10 cannot be compared as plain text, because "2" would wrongly look bigger than "10". Instead we compare them chunk by chunk as integers, walking both strings with two pointers.
Each round, an inner loop reads digits until the next dot, building one number with a = a * 10 + digit for version1 and the same for version2. This turns each dotted segment into a real integer.
We then compare the two chunk numbers: if a < b return -1, if a > b return 1. If they are equal we skip the dot and continue to the next chunk.
Because a finished string contributes 0 for any missing chunk, 1.0 and 1 compare as equal automatically — we keep looping while either pointer still has characters.
Example: 1.2 vs 1.10. First chunks 1 and 1 tie, then 2 vs 10: since 2 < 10, the result is -1.