How to Compare Version Numbers in Go – Interview Solution
This article explains the key steps for comparing dot‑separated version strings—ignoring leading zeros, handling different lengths, and performing left‑to‑right numeric comparison—accompanied by a complete Go implementation.
Version numbers consist of multiple revision numbers separated by "."; each segment may have leading zeros that should be ignored, and the length of version strings can differ (e.g., "1.0" vs "1.0.0"). Therefore the comparison must proceed from left to right, comparing numeric values of each segment.
The solution first splits both version strings by "." using strings.Split, then iterates over the corresponding segments, converting each to an integer with strconv.Atoi. If a segment in version1 is greater than the counterpart, the function returns 1; if smaller, it returns -1.
If the loop finishes without a decisive difference, the algorithm checks the remaining segments of the longer version. Any non‑zero segment in the longer version means that version is greater (treated as compared against an implicit 0 in the shorter version). The function finally returns 0 when all compared segments are equal.
func compareVersion(version1 string, version2 string) int {
// 1. split by "."
slicev1 := strings.Split(version1, ".")
slicev2 := strings.Split(version2, ".")
// 2. compare corresponding positions
i, j := 0, 0
for ; i < len(slicev1) && j < len(slicev2); i, j = i+1, j+1 {
val1, _ := strconv.Atoi(slicev1[i])
val2, _ := strconv.Atoi(slicev2[j])
if val1 > val2 {
// version1 larger
return 1
} else if val1 < val2 {
// version2 larger
return -1
}
}
// 3. remaining parts of version1 (treated as >0)
for i < len(slicev1) {
val1, _ := strconv.Atoi(slicev1[i])
i++
if val1 > 0 {
return 1
} else if val1 < 0 {
return -1
}
}
// 4. remaining parts of version2 (treated as >0)
for j < len(slicev2) {
val2, _ := strconv.Atoi(slicev2[j])
j++
if val2 > 0 {
return -1
} else if val2 < 0 {
return 1
}
}
// 5. all equal
return 0
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Nullbody Notes
Go backend development, learning open-source project source code together, focusing on simplicity and practicality.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
