Java no split


  • 0
    J

    didn't expect "1.0.0.0.0.0" equals "1". kind of weird.

        public int compareVersion(String version1, String version2) {
            int i = 0, j = 0;
            while (i < version1.length() && j < version2.length()) {
                int v1 = 0, v2 = 0;
                while (i < version1.length() && version1.charAt(i) != '.') v1 = v1 * 10 + version1.charAt(i++) - '0';
                while (j < version2.length() && version2.charAt(j) != '.') v2 = v2 * 10 + version2.charAt(j++) - '0';
                if (v1 < v2) return -1;
                if (v1 > v2) return 1;
                if (i < version1.length()) i++;
                if (j < version2.length()) j++;
            }
            if (i >= version1.length()) {
                while (j < version2.length()) {
                    if (version2.charAt(j) != '0' && version2.charAt(j) != '.') return -1;
                    j++;
                }
                return 0;
            }
            if (j >= version2.length()) {
                while (i < version1.length()) {
                    if (version1.charAt(i) != '0' && version1.charAt(i) != '.') return 1;
                    i++;
                }
                return 0; 
            }
            return 0;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.