您的位置:首页 > 其它

【Leetcode】Compare Version Numbers

2014-12-30 00:07 411 查看
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

这道题真心是debug最费劲的一道。。。各种考虑不到的情况

我的思路比较简单,就是通过‘.’split之后,一个一个数字去比较,其他的就是去debug了……

package testAndfun;

public class CompareVersionNum {
public static void main(String[] args){
CompareVersionNum cvn = new CompareVersionNum();
String input1 = new String("1.1");
String input2 = new String("1.01.0");
System.out.println(cvn.compareVersion(input1, input2));
}
public int compareVersion(String version1, String version2) {
if(!version1.contains(".")||!version2.contains("."))
if(Float.parseFloat(version1)==Float.parseFloat(version2))
return 0;
else
return Float.parseFloat(version1)>Float.parseFloat(version2)?1:-1;
String[] ver1 = new String[100];
String[] ver2 = new String[100];
ver1 = version1.split("\\.");
ver2 = version2.split("\\.");
int mark = 0;
if(ver1.length>ver2.length)
mark = Integer.parseInt(ver1[ver1.length-1]);

if(ver1.length<ver2.length)
mark = Integer.parseInt(ver2[ver2.length-1]);

for(int i=0;i<Math.min(ver1.length, ver2.length);i++){
//System.out.println(ver1[i]+"?"+ver2[i]);
//System.out.println(ver1.length+"长度"+ver2.length);

if(Integer.parseInt(ver1[i])>Integer.parseInt(ver2[i])||
(ver1[i]!=null&&ver2[i]==null))	return 1;
if(Integer.parseInt(ver1[i])<Integer.parseInt(ver2[i])||
(ver1[i]==null&&ver2[i]!=null))	return -1;
if(Integer.parseInt(ver1[i])==Integer.parseInt(ver2[i])
&&i==ver1.length-1&&i==ver2.length-1)	return 0;
}
if(mark==0)	return 0;
else
return ver1.length>ver2.length?1:-1;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: