zoukankan      html  css  js  c++  java
  • Compare Version Numbers

    Compare two version numbers version1 and version1.
    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

    注意一个特例: 1 和 1.0。

    所以 在比较完对应的位数之后,还要查看多的位数是不是均为0.

    还有就是在split(".") 时候,由于.是正则表达式中的符号,所以要转置。
     1 public class Solution {
     2     public int compareVersion(String version1, String version2) {
     3         String[] parts1 = version1.split("\.");
     4         String[] parts2 = version2.split("\.");
     5         int len1 = parts1.length;
     6         int len2 = parts2.length;
     7         int i = 0;
     8         for(; i < len1 && i < len2; i ++){
     9             if(Integer.valueOf(parts1[i]) > Integer.valueOf(parts2[i])) return 1;
    10             if(Integer.valueOf(parts2[i]) > Integer.valueOf(parts1[i])) return -1;
    11         }
    12         if(len1 > len2){
    13             while(i < len1){
    14                 if(Integer.valueOf(parts1[i++]) != 0) return 1;
    15             }
    16         }else if(len1 < len2){
    17             while(i < len2){
    18                 if(Integer.valueOf(parts2[i++]) != 0) return -1;
    19             }
    20         }
    21         return 0;
    22     }
    23 }
  • 相关阅读:
    Java对MongoDB的CRUD
    MongoDB数据库基本用法
    MySQL order by 排序结果不正确
    Linux shell 脚本 eq,ne,le,ge,lt,gt意义
    Linux shell 命令运行符 &,;,&& 区别
    Linux netstat 命令详解
    Linux ss 命令详解
    Linux sort 命令详解
    Linux sed 命令详解
    Linux xargs 命令详解
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4226404.html
Copyright © 2011-2022 走看看