Compare Version Numbers

来源:互联网 发布:两少一宽 胡 知乎 编辑:程序博客网 时间:2024/06/07 12:48

Compare Version Numbers

 Total Accepted: 25486 Total Submissions: 167858My Submissions

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

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

Show Tags
Have you met this question in a real interview? 
Yes
 
No

思路就是把每段的值计算出来,然后比较大小,直到比出来为止。

本来想用split方法来处理的,但用"."来切割一直报错。这里注意一下String的split函数的使用:

典型用法如下:

String ip = "192.168.1.1";
String a[] = ip.split("\\.");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}

注意要用”\\.“来切割,而不能只用”.“,因为''."是一个特殊字符,需要一个\来转义,而在正则表达式中\\表示一个\

本题的代码如下:

public class Solution {    public int compareVersion(String version1, String version2) {        int len1 = version1.length();        int len2 = version2.length();                int i = 0;        int a = 0;                int j = 0;        int b = 0;        while(i<len1 || j<len2){            while(i<len1 && version1.charAt(i)!='.'){                a = 10*a+Integer.parseInt(String.valueOf(version1.charAt(i)));                i++;            }            i++;                        while(j<len2 && version2.charAt(j)!='.'){                b = 10*b + Integer.parseInt(String.valueOf(version2.charAt(j)));                j++;            }            j++;            if(a>b){                return 1;            }else if(a<b){                return -1;            }else{                //这一段内version1和version2是相等的,将a,b清0,准备下一段的比较                a=0;                b=0;            }                 }        return 0;    }}


0 0
原创粉丝点击