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 }








  • 相关阅读:
    数组的处理
    bootstrap 列的排序
    bootstrap 偏移
    mysql数据库创建、删除数据库
    Spring 加载配置文件的方式
    MyBatis DAO层传递参数到mapping.xml 几种方式
    Python 正则表达式
    Python 之定时器
    Python学习
    获取鼠标经过位置的X、Y坐标
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4574377.html
Copyright © 2011-2022 走看看