String to Integer (atoi)

本贴最后更新于 2495 天前,其中的信息可能已经时移世易

题目描述

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.

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.

把字符串变成整数,超出范围的用最大值表示。最开始可以有空格,但不能有其他字符;后面可以有无效字符。

解题思路

用一个 boolean 标记是否已经开始数值计算,用 positive 存储'+/-'。用 long 存储返回值,一旦返回值超出范围,就返回最大值。

代码

class Solution {
    public int myAtoi(String str) {
        if (str == null || str.trim().length() == 0)
            return 0;
        str = str.trim();
        long ret = 0;
        boolean label = false;
        long positive = 1;
        for (int i = 0; i < str.length(); i++) {
            if (!label && (str.charAt(i) == '-' || str.charAt(i) == '+' || (str.charAt(i) >= '0' && str.charAt(i) <= '9'))) {
                if (str.charAt(i) == '-')
                    positive = -1;
                if (str.charAt(i) >= '0' && str.charAt(i) <= '9')
                    ret = ret + str.charAt(i) - '0';
                label = true;
            } else if (label && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
                ret *= 10;
                ret = ret + str.charAt(i) - '0';
            } else if (str.charAt(i) < '0' || str.charAt(i) > '9') {
                break;
            }
            if (ret * positive > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (ret * positive < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
        }
        ret *= positive;
        return (int)ret;
    }
}
  • 算法
    428 引用 • 254 回帖 • 24 关注
  • LeetCode

    LeetCode(力扣)是一个全球极客挚爱的高质量技术成长平台,想要学习和提升专业能力从这里开始,充足技术干货等你来啃,轻松拿下 Dream Offer!

    209 引用 • 72 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...