题解 | #比较版本号#
比较版本号
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[] nums1 = version1.split("\\.");
String[] nums2 = version2.split("\\.");
int res = 0;
int i = 0;
int j = 0;
while(i<nums1.length&&j<nums2.length){
String a = nums1[i++];
String b = nums2[j++];
int tmp = compareInt(a,b);
if(tmp<0){
return -1;
}
if(tmp>0){
return 1;
}
}
if(nums1.length == nums2.length){
return 0;
}else{
if(i<nums1.length){
while(i<nums1.length){
if(Integer.parseInt(nums1[i])!=0){
return 1;
}
i++;
}
}
if(j<nums2.length){
while(j<nums2.length){
if(Integer.parseInt(nums2[j])!=0){
return -1;
}
j++;
}
}
return 0;
}
}
private int compareInt(String a, String b) {
// TODO
int i = Integer.parseInt(a);
int j = Integer.parseInt(b);
return i-j;
}
}
