题解 | #比较版本号#
比较版本号
https://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7
package com.hhdd;
/**
* @Author huanghedidi
* @Date 2022/7/24 0:06
*/
public class 比较版本号 {
public static void main(String[] args) {
int res = compare("1.1", "1.01");
System.out.println("res = " + res);
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* <p>
* 比较版本号
*
* @param version1 string字符串
* @param version2 string字符串
* @return int整型
*/
public static int compare(String version1, String version2) {
// write code here
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
int i = 0;
while (i < v1.length && i < v2.length) {
String s1 = v1[i];
String s2 = v2[i];
if (Integer.parseInt(s1) > Integer.parseInt(s2)) {
return 1;
}
if (Integer.parseInt(s1) < Integer.parseInt(s2)) {
return -1;
}
i++;
}
if (i < v1.length) {
// 说明v1还有数
while (i < v1.length) {
// 只要i位置不是0,就是v1比较大,就返回1
if (Integer.parseInt(v1[i]) > 0) {
return 1;
}
i++;
}
// 说明完全一样 返回0
return 0;
}
if (i < v2.length) {
// 说明v1还有数
while (i < v2.length) {
// 只要i位置不是0,就是v1比较大,就返回1
if (Integer.parseInt(v2[i]) > 0) {
return -1;
}
i++;
}
// 说明完全一样 返回0
return 0;
}
return 0;
}
}
