Topic describes
You are given two version numbers version1 and version2, please compare them. // The version number consists of one or more revision numbers, each of which is connected by a '.'. Each revision number consists of multiple // digits and may contain leading zeros. Each version number contains at least one character. The revision number is numbered with // from left to right, and the subscript starts with 0. The leftmost revision number is subscript 0, and the next revision number is subscript 1. For example, 2.5.33 and 0.1 are valid version numbers. // When comparing version numbers, compare their revision numbers from left to right. When comparing revision numbers, only ignore any integer values after leading zeros more than //. That is, revision number 1 is equal to revision number 001. If the // version number does not specify a revision number at a subscript, the revision number is treated as 0. For example, version 1.0 is less than version // version 1.1 because they have the same revision number with subscript 0, while the revision number with subscript 1 is 0 and 1, respectively, and // 0 < 1. // Returns 1 if version1 > version2, -1 if version1 < version2, and 0 otherwise.Copy the code
Answer key
// Double pointer // define double pointer I and j, while loop terminates when I and j both iterate over the version number. // For version1, the I pointer while loops through the version1 digits until '.' is encountered, and the iterated digits are stored in A, where the digits already stored in A are raised by one digit as the high level. The newly traversed number is added as the low order, and // remember to subtract '0' to int. // for version2, the j pointer while loop iterates over the numbers in version2 as above and stores them in b. If I and j move to the right, skip '.' and iterate over the next revision number. // // execution time: 0 ms, beat 100.00% user // memory consumption in all Java commits: Class Solution {public int compareVersion(String version1, String version2) { int i = 0, j = 0; while (i < version1.length() || j < version2.length()) { int a = 0, b = 0; while (i < version1.length() && version1.charAt(i) ! = '.') { a = a * 10 + version1.charAt(i++) - '0'; } while (j < version2.length() && version2.charAt(j) ! = '.') { b = b * 10 + version2.charAt(j++) - '0'; } if (a > b) return 1; else if (a < b) return -1; i++; j++; } return 0; }}Copy the code