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);
}
}
网友评论