• 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 }
  • 相关阅读:
    5分钟了解为什么学习Go
    jieba gensim 相似度实现
    functiils.lru_cache缩短递归时间
    python深浅copy和赋值
    ajax上传文件 基于jquery form表单上传文件
    form组件类 钩子函数验证
    基于jquery读取input上传的文件内容
    MongonDB指令汇总
    冥想编程
    《如何阅读一本书》读书笔记
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4226404.html
Copyright © 2020-2023  润新知