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
https://leetcode.com/problems/compare-version-numbers/
恶心题,看我给的几个Test Case吧。
1 /** 2 * @param {string} version1 3 * @param {string} version2 4 * @return {number} 5 */ 6 var compareVersion = function(version1, version2) { 7 var v1Arr = version1.split('.'); 8 var v2Arr = version2.split('.'); 9 var len = Math.max(v1Arr.length, v2Arr.length); 10 for(var i = 0; i < len; i++){ 11 var v1 = format(v1Arr[i]); 12 var v2 = format(v2Arr[i]); 13 if(v1 > v2){ 14 return 1; 15 }else if(v1 < v2){ 16 return -1; 17 } 18 } 19 return 0; 20 21 function format(num){ 22 if(!num){ 23 return 0; 24 } 25 var res = parseInt(num); 26 if(isNaN(res)){ 27 res = 0; 28 } 29 return res; 30 } 31 }; 32 33 function test(){ 34 console.log(compareVersion('1','0')); //1 35 console.log(compareVersion('1.2','1.10')); //-1 36 console.log(compareVersion('1.1','1.10')); //-1 37 console.log(compareVersion('01','1')); // 0 38 console.log(compareVersion('1.0.0.0.0.0.0','1.0.0')); // 0 39 }