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

    Credits:
    Special thanks to @ts for adding this problem and creating all test cases.

    大致题意:比较版本号,比较的两个元素由顿号分割的字符串组成

    int compareVersion(string version1, string version2) {
        version1+='.';
        version2+='.';
        int l1=version1.length(),l2=version2.length(),i,j,num1,num2;
        i=0;
        j=0;
        while (i<l1 || j<l2)
        {
            num1=0;
            while (i<l1 && version1[i]!='.')
            {
                num1=num1*10+version1[i]-'0';
                ++i;
            }
    
            if (version1[i]=='.') ++i;
            num2=0;
            while (j<l2 && version2[j]!='.')
            {
                num2=num2*10+version2[j]-'0';
                ++j;
            }
            if (version2[j]=='.') ++j;
            if (num1!=num2)
                return num1>num2?1:-1;
        }
        return 0;  
    }

    这个题有意思的在于统一化的处理

    先在串尾加顿号,这样每次都可以以顿号为判定条件

    其次while (i<l1 || j<l2)这一句也很有意思,我开始写的是 while(i<l1 && j<l2),这样的话每次对串长不同的要在while后判定处理

    if (i==l1 && j!=l2) return -1;
        else if (i!=l1 && j==l2) return 1;

    因为前面都相同,没完的串肯定版本新,于是光荣的WA了,有数据是1 1.0,23333

    所以在一个串结束后,未完串是否为0,也是要看的,这里仅需要把循环条件修改就行了

  • 相关阅读:
    logging模块-logging.basicConfig、logger.setLevel、handler.setLevel优先级
    Python标准模块--logging(转载)
    第三节,入门知识和windows系统安装python环境
    第二节windows系统下Xshell 5软件远程访问虚拟机 Linux系统
    第一节windows系统安装虚拟机VMware 软件
    数学数列
    java String
    linux eclipse 报错过时的方法
    java.util.Random 类
    java uitl
  • 原文地址:https://www.cnblogs.com/mintmy/p/4191355.html
Copyright © 2011-2022 走看看