当前位置:网站首页>Comparison version number [leetcode]

Comparison version number [leetcode]

2022-06-26 07:52:00 Don't hit me, it hurts!

Compare version number

describe : Here are two version numbers version1 and version2 , Please compare them .

The version number consists of one or more revision numbers , Each revision number consists of a ‘.’ Connect . Each revision number consists of Multiple digits form , May contain Leading zero . Each version number contains at least one character . The revision number is numbered from left to right , Subscript from 0 Start , The leftmost revision number is subscript 0 , The next revision number is subscript 1 , And so on . for example ,2.5.33 and 0.1 All valid version numbers .

When comparing version numbers , Please compare their revision numbers from left to right . When comparing revision numbers , Just compare Ignore any integer values after leading zeros . in other words , Revision number 1 And revision number 001 equal . If the version number does not specify a revision number at a subscript , Then the amendment number shall be deemed to be 0 . for example , edition 1.0 Less than version 1.1 , Because they are subscript 0 The revision number of is the same , And the subscript is 1 The revision numbers of are respectively 0 and 1 ,0 < 1 .

The return rule is as follows :

  • If version1 > version2 return 1,
  • If version1 < version2 return -1,
  • In addition, return to 0.

Tips :

  • 1 <= version1.length, version2.length <= 500
  • version1 and version2 Contains only numbers and ‘.’
  • version1 and version2 All are Valid version number
  • version1 and version2 All revision numbers of can be stored in 32 An integer in

Answer key

Ideas :

  • 1. adopt . Split the string , Get array
  • 2. Take the maximum length of both , As array length , Use of insufficient length 0 completion
  • 3. Compare elements at the same position in the array
var compareVersion = function(version1, version2) {
    
    // 1. adopt . Split the string 
    let v1 = version1.split('.');
    let v2 = version2.split('.');
    // 2. Take the maximum length of both , As array length 
    let len = (v1.length>v2.length ? v1.length:v2.length);
    for(let i=0;i<len;++i){
    
        //  Use of insufficient length  0  completion 
        let num1 = v1[i]?parseInt(v1[i]):0;
        let num2 = v2[i]?parseInt(v2[i]):0;
        // 3. Compare elements at the same position in the array 
        if(num1>num2) return 1;
        else if(num1<num2) return -1;
    }
    //  All positions are relatively complete , Show the same 
    return 0

};

The article links : Compare version number 【leetcode】
* Please quote from QW’s Blog!*

原网站

版权声明
本文为[Don't hit me, it hurts!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170609120015.html