165 8

165. Compare Version Numbers

class Solution {
    public int compareVersion(String version1, String version2) {
        String[] levels1 = version1.split("\\.");
        String[] levels2 = version2.split("\\.");
        
        int length = Math.max(levels1.length, levels2.length);
        for(int i = 0; i < length; i++){
            Integer v1 = i < levels1.length ? Integer.parseInt(levels1[i]) : 0;
            Integer v2 = i < levels2.length ? Integer.parseInt(levels2[i]) : 0;
            int compare = v1.compareTo(v2);
            if(compare != 0){
                return compare;
            }
        }
        return 0;
    }
}

8. String to Integer (atoi)

sign: 正负号

index: 当前索引。

class Solution {
    public int myAtoi(String str) {
        str = str.trim();
        if(str == null || str.length() == 0) return 0;
        
        int sign = 1;
        int index = 0;
        char c = str.charAt(0);
        if(c == '+'){
            sign = 1;
            index++;
        }else if(c == '-'){
            sign = -1;
            index++;
        }
        
        long sum = 0;
        for(int i = index; i < str.length(); i++){
            if(!Character.isDigit(str.charAt(i))){
                return (int)sum * sign;
            }
            sum = sum * 10 + str.charAt(i) - '0';
            if(sign == 1 && sum > Integer.MAX_VALUE){
                return Integer.MAX_VALUE;
            }
            if(sign == -1 && (-1)*sum < Integer.MIN_VALUE){
                return Integer.MIN_VALUE;
            }
        }
        return (int)sum * sign;
    }
}

 

上一篇:165-286. 墙与门


下一篇:165_初识Java_程序-进程-线程_学习