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;
        }
    }
    
  • 相关阅读:
    预防新型冠状病毒科普宣传网站
    四则运算
    结对审查
    最大子段和
    单元自动测试Junit
    浅谈过去,畅想未来
    第一次的结对编程
    代码审查
    单元测试
    junit4单元测试
  • 原文地址:https://www.cnblogs.com/optor/p/8644917.html
Copyright © 2011-2022 走看看