zoukankan      html  css  js  c++  java
  • [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 }








  • 相关阅读:
    SVN项目提交报错
    Post请求报文压缩
    mysql表结构的修改-sql记录
    项目内添加quartz定时任务
    Nginx配置-通过nginx访问项目
    Mysql的使用 -简单的索引
    使用git第一次成功,记录
    Spring P命名空间 02
    Mybatis 一级、二级缓存
    延迟加载
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4574377.html
Copyright © 2011-2022 走看看