题解 | #比较版本号#

比较版本号

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;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务