08.字符串转换位整数

题目:

 

 

 

 提交:

class Solution {
    public int myAtoi(String str) {
         str = str.trim();
        if (str == null || str.length() == 0) return 0;

        // + - 号
        char firstChar = str.charAt(0);
        int sign = 1;
        int start = 0;
        long res = 0;
        if (firstChar == '+') {
            sign = 1;
            start++;
        } else if (firstChar == '-') {
            sign = -1;
            start++;
        }

        for (int i = start; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {
                return (int) res * sign;
            }
            res = res * 10 + str.charAt(i) - '0';
            if (sign == 1 && res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (sign == -1 && res > Integer.MAX_VALUE) return Integer.MIN_VALUE;
        }
        return (int) res * sign;
    }
}

评论:奇葩输入太多,只能参考别人的代码

posted @ 2019-09-01 14:08  byebai95  阅读(219)  评论(0编辑  收藏  举报