题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 比较版本号
* @param version1 string字符串
* @param version2 string字符串
* @return int整型
*/
public int compare (String version1, String version2) {
// write code here
String[] str1 = version1.split("\\.");
String[] str2 = version2.split("\\.");
int length = Math.min(str1.length, str2.length);
int i = 0;
for (; i < length; i++) {
if (!str1[i].isEmpty() && !str2[i].isEmpty()) {
if (Integer.parseInt(str1[i]) < Integer.parseInt(str2[i])) {
return -1;
} else if (Integer.parseInt(str1[i]) > Integer.parseInt(str2[i])) {
return 1;
}
} else if (str1[i].isEmpty()) {
if (!str2[i].isEmpty() && (Integer.parseInt(str2[i]) != 0)) {
return -1;
}
} else if (str2[i].isEmpty()) {
if (!str1[i].isEmpty() && (Integer.parseInt(str1[i]) != 0)) {
return 1;
}
}
}
if (str1.length > str2.length) {
for (; i < str1.length; i++) {
if (!str1[i].isEmpty()&& (Integer.parseInt(str1[i]) != 0)) {
return 1;
}
}
} else if (str1.length < str2.length) {
for (; i < str2.length; i++) {
if (!str2[i].isEmpty()&& (Integer.parseInt(str2[i]) != 0)) {
return -1;
}
}
}
return 0;
}
}
华为HUAWEI工作强度 1383人发布
查看58道真题和解析