zoukankan      html  css  js  c++  java
  • LeetCode OJ: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

    注意可能会出现前置0的情况,所以分为小数点钱与小数点后转换成数字来判断,代码如下:

     1 class Solution {
     2 public:
     3     int compareVersion(string version1, string version2) {
     4         int i1, i2;
     5         int val1, val2;
     6         for(i1 = 0, i2 = 0; i1 < version1.size() || i2 < version2.size(); ++i1, ++i2){
     7             val1 = 0;
     8             for(; i1 < version1.size(); ++i1){
     9                 if(version1[i1] == '.')
    10                     break;
    11                 val1 = val1 * 10 + version1[i1] - '0';
    12             }
    13             val2 = 0;
    14             for(; i2 < version2.size(); ++i2){
    15                 if(version2[i2] == '.')
    16                     break;
    17                 val2 = val2 * 10 + version2[i2] - '0';
    18             }
    19             if(val1 > val2)
    20                 return 1;
    21             else if(val1 < val2) 
    22                 return -1;
    23         }
    24         return 0;
    25     }
    26 };
  • 相关阅读:
    抽象工厂模式
    外观模式
    策略模式
    状态模式
    观察者模式
    装饰者模式
    模板方法模式
    适配器模式
    中介者模式
    组合模式
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4937315.html
Copyright © 2011-2022 走看看