题解 | #比较版本号#
比较版本号
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 int i = 0; int j = 0; while (i < version1.length() || j < version2.length()) { int num1 = 0; int num2 = 0; for (int k = i; k <= version1.length(); k++) { if (k == version1.length() || '.' == version1.charAt(k)) { num1 = Integer.parseInt(version1.substring(i, k)); i = k + 1; break; } } for (int k = j; k <= version2.length(); k++) { if (k == version2.length() || '.' == version2.charAt(k)) { num2 = Integer.parseInt(version2.substring(j, k)); j = k + 1; break; } } if (num1 < num2) { return -1; } if (num1 > num2) { return 1; } } return 0; } }