• [LeetCode][JavaScript]Compare Version Numbers


    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 }








  • 相关阅读:
    AJAX请求头Content-type
    原 layer父子页面交互
    layer.closeAll()无法关闭弹窗的解决办法之一
    成员函数的重载,覆盖与隐藏
    const限定符用法汇总
    构造函数和析构函数的调用时机
    MFC 消息映射、分派和传递
    C++对象模型
    函数指针与虚函数表
    数据类型与内存映像
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4574377.html
Copyright © 2020-2023  润新知