Compare Version Numbers

medium two pointers string

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.

Inputversion1 = "1.2", version2 = "1.10"
Output-1
Compare chunk by chunk: (1, 1) equal, then (2, 10) → 2 < 10 so version1 < version2 → return -1.

def 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;
}
Time: O(n + m) Space: O(1)