题解 | #比较版本号#

比较版本号

http://www.nowcoder.com/practice/2b317e02f14247a49ffdbdba315459e7

import java.util.*;
import java.math.BigInteger;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 比较版本号
     * @param version1 string字符串 
     * @param version2 string字符串 
     * @return int整型
     */
    public int compare (String version1, String version2) {
        // write code here
        String[] num1 =  version1.split("\\.");
        String[] num2 =  version2.split("\\.");

        int n1 = num1.length;
        int n2 = num2.length;

        int n = Math.max(n1, n2);

        for (int i = 0; i < n; i++) {
            BigInteger i1 = new BigInteger(i < n1 ? num1[i] : "0");
            BigInteger i2 = new BigInteger(i < n2 ? num2[i] : "0");
            if (!i1.equals(i2)) {
                return i1.compareTo(i2) > 0 ? 1 : -1;
            }
        }

        return 0;
    }
}
全部评论

相关推荐

01-12 09:24
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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