美文网首页
LeetCode每日一题:string to integer a

LeetCode每日一题:string to integer a

作者: yoshino | 来源:发表于2017-07-05 17:02 被阅读42次

    问题描述

    Implement atoi to convert a string to an integer.
    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
    spoilers alert... click to show requirements for atoi.
    Requirements for atoi:
    The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
    The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
    If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
    If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

    问题分析

    模拟字符串转成int函数,atoi。注意处理好符号和溢出问题即可。

    代码实现

    public int atoi(String str) {
            str = str.trim();
            if (str.length() == 0) return 0;
            String result = "";
            int inx = 0;
            String minus = "";
            if (str.charAt(0) == '-') {
                minus = "-";
                inx++;
            } else if (str.charAt(0) == '+') {
                minus = "+";
                inx++;
            }
            for (int i = inx; i < str.length(); i++) {
                if (str.charAt(i) >= '0' && str.charAt(i) <= '9') result = result + str.charAt(i);
                else break;
            }
            if (result == "") return 0;
            if (Long.valueOf(minus + result) > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (Long.valueOf(minus + result) < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            return Integer.valueOf(minus + result);
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:string to integer a

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