8. String to Integer (atoi)

题目:

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.

链接:http://leetcode.com/problems/string-to-integer-atoi/

题解:

这道题试了好多次才ac,在Microsoft onsite的第三轮里也被问到过如何解决和测试。主要难点就是处理各种corner case。假如面试中遇到,一定要和面试官多沟通交流,确定overflow,underflow以及invalid的时候,应该返回什么值。判断时不可以使用long才hold溢出情况,一般都是比较当前数值和Integer.MAX_VALUE / 10 或者Integer.MIN_VALUE / 10。

以下是一个AC解法,主要方法是

1). 判断输入是否为空

2). 用trim()去除string前后的空格

3). 判断符号

4). 假如符号位后连续几位是有效的数字,对数字进行计算,同时判断是否overflow或者underflow。

5). 返回数字

public class Solution {

    public int myAtoi(String str) {

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

            return 0;

        str = str.trim();

        int index = 0, result = 0;

        boolean isNeg = false;

   

        if(str.charAt(index) == '+')

            index ++;

        else if(str.charAt(index) == '-'){

            isNeg = true;

            index ++;

        }

        

        while(index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9'){     //deal with valid input numbers

            if(result > Integer.MAX_VALUE / 10){

                return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE;                           // case "      -11919730356x", the result should be 0?

            } else if( result == Integer.MAX_VALUE / 10){                       

                if((!isNeg) && ((str.charAt(index) - '0') > Integer.MAX_VALUE % 10) ) 

                    return Integer.MAX_VALUE;

                else if (isNeg && ((str.charAt(index) - '0') > (Integer.MAX_VALUE % 10 + 1)))

                    return Integer.MIN_VALUE;

            }

            result = result * 10 + (str.charAt(index) - '0');  

            index ++; 

        }

        

        return isNeg ? -result : result;

    }

}

 

测试:

1. "+-2"

2. "    123  456"

3. "      -11919730356x"

4. "2147483647"

5. "-2147483648"

6. "2147483648"

7. "-2147483649"

Reference:

 

你可能感兴趣的:(Integer)