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

8. String to Integer (atoi)

时间:2017-08-11 10:47:30      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:ted   yourself   boolean   ignore   hose   been   discard   any   tin   

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.

这道题还是对于Integer的处理,在Reverse Integer这道题中我有提到,这种题的考察重点并不在于问题本身,而是要注意corner case的处理,整数一般有两点,一个是正负符号问题,另一个是整数越界问题。思路比较简单,就是先去掉多余的空格字符,然后读符号(注意正负号都有可能,也有可能没有符号),接下来按顺序读数字,结束条件有三种情况:(1)异常字符出现(按照C语言的标准是把异常字符起的后面全部截去,保留前面的部分作为结果);(2)数字越界(返回最接近的整数);(3)字符串结束。代码如下:

public int myAtoi(String str) {
        
        if (str == null) {
            return 0;
        }
        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }
        
        boolean isNeg = false;       
        int i = 0;
        if (str.charAt(0) == ‘-‘) {
            i++;
            isNeg =  !isNeg;
        } else if (str.charAt(0) == ‘+‘) {
            i++;
        }
        int ans = 0;
        while (i < str.length()) {
            if (str.charAt(i) < ‘0‘|| str.charAt(i) > ‘9‘) {
                break;
            }
            int digit =  (int)(str.charAt(i) - ‘0‘);
            if (isNeg && ans > -((Integer.MIN_VALUE + digit) / 10)) {
                return Integer.MIN_VALUE;
            }
            if (!isNeg && ans > ((Integer.MAX_VALUE - digit) / 10)) {
                return Integer.MAX_VALUE;
            }
            ans = ans * 10 + digit;
            i++;
        }
        if (ans == 0) {
            return 0;
        }else if (isNeg) {
            return -ans;
        } else {
            return ans;
        }
    }

we should pay more attention to the corner case. One is that is the result positive or negative? the other is when is the correct value out of the range of representable values?

Besides, according to the question, we should trim white space in the String, and disern the additional characters in the string.

8. String to Integer (atoi)

标签:ted   yourself   boolean   ignore   hose   been   discard   any   tin   

原文地址:http://www.cnblogs.com/apanda009/p/7344207.html

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