Compare Version Numbers

medium Strings

Problem

Two version numbers are given as words of numbers separated by dots (for example 1.2.10). Compare them part by part from the left as whole numbers (so 10 is bigger than 9, and 01 equals 1). A missing part counts as 0, so 1.0 equals 1.0.0. Print 1 if the first version is newer, -1 if the second is newer, and 0 if they are equal.

Constraints

  • 1 <= parts <= 100
  • each part is a non-negative integer, at most 9 digits

Examples

Input

1.2.10 1.2.9

Output

1

Input

1.0 1.0.0

Output

0

Solutions

Best approachTime O(n)Space O(n)

Comparing the versions as text is wrong: 1.2.10 looks smaller than 1.2.9 as text. Splitting at the dots and comparing each part as a number is the right way. Padding with zeros is the reason that 1.0 and 1.0.0 are equal.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process two words.
 * Input   : Two words separated by a space.
 * Output  : 1, -1 or 0.
 * Approach: Two version words.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int solve(String a, String b) {
        // Step 1: Split both versions into their number parts.
        String[] first = a.split("\\.");
        String[] second = b.split("\\.");
        int length = Math.max(first.length, second.length);
        for (int i = 0; i < length; i++) {
            // Step 2: A missing part counts as 0. Parsing as numbers makes "01" equal to "1" and 10 bigger than 9.
            long x = i < first.length ? Long.parseLong(first[i]) : 0;
            long y = i < second.length ? Long.parseLong(second[i]) : 0;
            if (x != y) {
                return x > y ? 1 : -1;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String a = scanner.next();
        String b = scanner.next();
        System.out.println(solve(a, b));
    }
}
Hints (1)
  1. Why does text comparison fail for 1.2.10 and 1.2.9?