public static void main(String[] args) {
// TODO Auto-generated method stub
String v1 = "6.6.3.5.6";
String v2 = "6.6.3.5a";
long t1=System.currentTimeMillis();
int result=compareVersionStr(v1, v2);
System.out.println("time costs:"+(System.currentTimeMillis()-t1)+" result:"+result);
}
public static int compareVersionStr(String v1, String v2) {
if (v1 == null || v2 == null) {
return COMPARE_VERSION_EXCEPTION;
}
v1 = v1.trim();
v2 = v2.trim();
boolean empty1 = v1.length() == 0;
boolean empty2 = v2.length() == 0;
if (!empty1 && empty2) {
return COMPARE_VERSION_GREATER;
}
if (empty1 && !empty2) {
return COMPARE_VERSION_SMALLER;
}
if (empty1 && empty2) {
return COMPARE_VERSION_EQUAL;
}
if (!v1.contains(".")) {
v1 = v1 + ".";
}
if (!v2.contains(".")) {
v2 = v2 + ".";
}
int firstIndex1 = v1.indexOf(".");
int firstIndex2 = v2.indexOf(".");
System.out.println("firstIndex1:" + firstIndex1 + " firstIndex2:"
+ firstIndex2);
String firstVer1 = v1.substring(0, firstIndex1);
String firstVer2 = v2.substring(0, firstIndex2);
System.out.println("firstVer1:" + firstVer1 + " firstVer2:"
+ firstVer2);
int a = 0, b = 0;
for (int i = 0; i < firstVer1.length(); i++) {
a += firstVer1.charAt(i);
}
for (int i = 0; i < firstVer2.length(); i++) {
b += firstVer2.charAt(i);
}
if (a > b) {
return COMPARE_VERSION_GREATER;
} else if (a < b) {
return COMPARE_VERSION_SMALLER;
} else {
String subVer1 = v1.substring(firstIndex1 + 1, v1.length());
String subVer2 = v2.substring(firstIndex2 + 1, v2.length());
System.out.println("subVer1:" + subVer1 + " subVer2:" + subVer2);
return compareVersionStr(subVer1, subVer2);
}
}
版本比较算法
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...