zoukankan      html  css  js  c++  java
  • 面试题67:把字符串转换成整数

    题目比较简单,主要是考察异常情况得处理:

    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        public static void main(String[] args) {
            Solution s = new Solution();
    //        System.out.println(s.strToInt("123"));
    //        System.out.println(s.strToInt(""));
    //        System.out.println(s.strToInt(null));
            System.out.println(s.strToInt("-1234"));
        }
    
        public int strToInt(String s) {
            if (s == null || s.equals("")) {
                throw new IllegalArgumentException("s value is illegal.");
            }
    
            boolean minus = false;
            if (s.charAt(0) == '+' || s.charAt(0) == '-') {
                if (s.charAt(0) == '-') {
                    minus = true;
                }
                s = s.substring(1);
            }
    
            int res = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) < '0' || s.charAt(i) > '9') {
                    throw new IllegalArgumentException("s value is illegal.");
                }
                res = res * 10 + (s.charAt(i) - '0');
            }
    
            if (minus) {
                res = -res;
            }
    
            return res;
        }
    }
    
  • 相关阅读:
    Google 嘘! 嘘!
    zabbix fast
    zabbix
    kernel update
    列表推导
    Ddos 反射性防护 simple
    file cycle
    Scala
    Hadoop
    数据库
  • 原文地址:https://www.cnblogs.com/optor/p/8644917.html
Copyright © 2011-2022 走看看