zoukankan      html  css  js  c++  java
  • <Math> 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;
        }
    }
  • 相关阅读:
    centos7 yum 方式安装nginx
    在Windows系统下用命令把应用程序添加到系统服务
    WPF内置命令
    Json解析实例
    端口占用的问题
    WPF里的报警闪烁效果
    python类中的一些神奇方法
    python中交换两个变量值的方法
    lambda应用
    python函数不定长参数
  • 原文地址:https://www.cnblogs.com/Afei-1123/p/11871295.html
Copyright © 2011-2022 走看看