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 }
  • 相关阅读:
    Servlet-获取页面的元素的值的方式以及区别
    Http请求-get和post的区别
    Servlet-xml配置简介以及url-pattern简介
    javaweb目录结构简介
    Servlet-生命周期简介
    tomcat-四种运行模式和三种部署模式(优化)
    命名空间System.IO
    Dictionary 字典
    导出-以虚拟表的形式获取数据源
    导入excel-uploadify+npoi
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4226404.html
Copyright © 2011-2022 走看看