题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
import java.util.*; public class Solution { public int compare (String version1, String version2) { String[] v1 = version1.split("\\."); int v1l = v1.length; String[] v2 = version2.split("\\."); int v2l = v2.length; StringBuilder sb = new StringBuilder(); if(v1l > v2l){ sb.append(version2); for(int i = 0; i < v1l - v2l; i++){ sb.append(".0"); } version2 = sb.toString(); } if (v1l < v2l) { sb.append(version1); for(int i = 0; i < v2l - v1l; i++){ sb.append(".0"); } version1 = sb.toString(); } String[] split1 = version1.split("\\."); int spl = v1.length; String[] split2 = version2.split("\\."); for (int i = 0; i < spl; i++) { if (Integer.parseInt(split1[i]) > Integer.parseInt(split2[i])) return 1; if (Integer.parseInt(split1[i]) < Integer.parseInt(split2[i])) return -1; } return 0; } }