面试题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;
    }
}
posted @ 2018-03-25 15:37  optor  阅读(129)  评论(0编辑  收藏  举报