题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 比较版本号 * @param version1 string字符串 * @param version2 string字符串 * @return int整型 */ function compare(version1, version2) { // write code here let v1 = version1.split("."); let v2 = version2.split("."); const maxLength = Math.max(v1.length, v2.length); const diff = v1.length - v2.length; const fill = new Array(Math.abs(diff)).fill(0); diff > 0 ? (v2 = v2.concat(fill)) : (v1 = v1.concat(fill)); for (let i = 0; i < maxLength; i++) { if (parseInt(v1[i]) > parseInt(v2[i])) { return 1; } if (parseInt(v1[i]) < parseInt(v2[i])) { return -1; } } return 0; } module.exports = { compare: compare, };
解题思路:字符串切割成数组,然后填补长度差,再一一比较
#比较版本号#