前端框架选型是企业提升开发效率与用户体验的关键因素
637
2022-11-11
165. Compare Version Numbers
Compare two version numbers version1 and version2. If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character. The . character does not represent a decimal point and is used to separate number sequences. For instance, 2.5 is not “two and a half” or “half way to version three”, it is the fifth second-level revision of the second first-level revision.
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
Credits: Special thanks to @ts for adding this problem and creating all test cases.
class Solution { public int compareVersion(String version1, String version2) { String[] versionArray1 = version1.split("\\."); String[] versionArray2 = version2.split("\\."); int len1 = versionArray1.length; int len2 = versionArray2.length; int len = len1 <= len2 ? len1 : len2; //共有版本号部分,从前向后比较对应位置数字 int x1, x2; for (int i = 0; i < len; i++) { x1 = Integer.parseInt(versionArray1[i]); x2 = Integer.parseInt(versionArray2[i]); if (x1 > x2) { return 1; } else if (x1 < x2) { return -1; } } //共有版本号相等的情况下,谁的版本号段数更多且多余部分不全为0,谁的版本更新 if (len1 > len2) { for (int i = len; i < len1; i++) { if (Integer.parseInt(versionArray1[i]) > 0) { return 1; } } } else if (len1 < len2) { for (int i = len; i < len2; i++) { if (Integer.parseInt(versionArray2[i]) > 0) { return -1; } } } return 0; }}
class Solution { public int compareVersion(String version1, String version2) { version1 = version1 + "."; version2 = version2 + "."; int l1 = version1.length(); int l2 = version2.length(); int i=0, j=0, v1, v2; while(i
class Solution { public int compareVersion(String v1, String v2) { int p1 = 0; int p2 = 0; while(p1 < v1.length() || p2 < v2.length()){ int e1 = getNextChunk(p1, v1); int e2 = getNextChunk(p2, v2); int c1 = 0; int c2 = 0; if(e1 != p1) c1 = Integer.parseInt(v1.substring(p1, e1)); if(e2 != p2) c2 = Integer.parseInt(v2.substring(p2, e2)); if(c1 != c2) return c1 > c2 ? 1 : -1; p1 = ++e1; p2 = ++e2; } return 0; } int getNextChunk(int start, String str){ while(start < str.length() && str.charAt(start) != '.'){ start++; } return start; } }
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~