美文网首页
leetcode 8 字符串转换整数 (atoi)

leetcode 8 字符串转换整数 (atoi)

作者: justonemoretry | 来源:发表于2019-12-06 00:00 被阅读0次

    这个题主要是要考虑清楚各种字符串组合情况,比如"+-2","+0 123"这种,需要处理好第一个非空字符,这个可以为正负号和数字,后面的就只能是数字了,还有就是各种临界情况。

    class Solution {

        public int myAtoi(String str) {

            if (null == str || 0 == str.length()) {

                return 0;        

            }

            int res = 0;

            int sign = 1;

            int i = 0;

            while (i < str.length() && ' ' == str.charAt(i)) {

                i++;

            }

            if (i == str.length()) {

                return 0;

            }

            // 处理第一个非空白字符

            char firstChar = str.charAt(i);

            if ('+' == firstChar || '-' == firstChar) {

                sign = '+' == firstChar ? 1 : -1;

                i++; 

            }

            for (; i < str.length(); i++) {

                char c = str.charAt(i);

                // 后续字符不是数字直接返回

                if (c < '0' || c > '9') {

                    return sign * res;        

                }

                if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && c > '7')) {

                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;        

                }

                res = res * 10 + (c - '0');       

            }

            return sign * res;

        }

    }

    相关文章

      网友评论

          本文标题:leetcode 8 字符串转换整数 (atoi)

          本文链接:https://www.haomeiwen.com/subject/xpqsgctx.html