码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: String to Integer (atoi)

时间:2015-03-05 20:48:00      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

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.

关于atoi的问题网上也有很多,这里提出我所想的:

1:输入为null或者””字符:

if (str == null || "".equals(str))
        {
//            System.out.println("输入格式错误! kong");
            return 0;
        }

2:含有英文字符:

String regEx = "([a-zA-Z]+)";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find())
        {
//            System.out.println("输入格式错误!");
            return 0;
        }

3:浮点数

CharSequence cs = ".";
if (str.contains(cs))
        {
//            System.out.println("输入格式错误! . . .");
            return 0;
        }

4:正数与负数的考虑:

if (str.startsWith("-"))
        {
            str = str.substring(1);
            flag = false;
        }
        result = Integer.parseInt(str);
        if (!flag)
        {
            result = result * (-1);
        }

5:关于科学计数法的表示,没有考虑,感觉有点复杂。

你以为上面就完了么?

Runtime Error Message:     Line 34: java.lang.NumberFormatException: For input string: "+-2"
Last executed input:     "+-2"

因此它的输入可能出现”+-2”,”++2”, “--2”等情况:

CharSequence cs1 = "+";
CharSequence cs2 = "-";
for (int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i) == ‘+‘ || str.charAt(i) == ‘-‘)
            {
                count++;
            }
        }
if (count >= 2)
        {
            return 0;
        }

出现空格:

Runtime Error Message:     Line 41: java.lang.NumberFormatException: For input string: " 010"
Last executed input:     " 010"
str = str.trim();

result的计算方法:

for (int i = 0; i < str.length(); i++)
        {
            if ((str.charAt(i) >= ‘a‘ && str.charAt(i) <= ‘z‘)
                    || (str.charAt(i) >= ‘A‘ && str.charAt(i) <= ‘Z‘)
                    || str.charAt(i) == ‘ ‘ || str.charAt(i) == ‘\t‘)
            {
                break;
            }
            if (str.charAt(i) >= ‘0‘ && ‘9‘ >= str.charAt(i))
            {
                result = result * 10 + (str.charAt(i) - ‘0‘);
                if (result > Integer.MAX_VALUE && flag)
                {
                    return Integer.MAX_VALUE;
                }
                if (result > Integer.MAX_VALUE && !flag)
                {
                    return Integer.MIN_VALUE;
                }
            }
        }

其中:

if ((str.charAt(i) >= ‘a‘ && str.charAt(i) <= ‘z‘)
                    || (str.charAt(i) >= ‘A‘ && str.charAt(i) <= ‘Z‘)
                    || str.charAt(i) == ‘ ‘ || str.charAt(i) == ‘\t‘)

考虑输入中含有字符,空格,tab等情况,不是舍弃值,而是把之前的值保存下来;

if (str.charAt(i) >= ‘0‘ && ‘9‘ >= str.charAt(i))
            {
                result = result * 10 + (str.charAt(i) - ‘0‘);
                if (result > Integer.MAX_VALUE && flag)
                {
                    return Integer.MAX_VALUE;
                }
                if (result > Integer.MAX_VALUE && !flag)
                {
                    return Integer.MIN_VALUE;
                }
            }

这里的result是long类型的,因为考虑到输入可能含有极值的情况,通过flag可以控制正数与负数的流程,最大数“2147483647”,最小数“-2147483648”,完成。

LeetCode: String to Integer (atoi)

标签:

原文地址:http://www.cnblogs.com/dslover/p/4316584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!