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;
    }
}

Python:

Java式Python... sigh,不知道什么时候才可以写得优雅简练。   检查Python里字符是否为数字一般有两种方法,一种是c.isdigit(), 另外可以尝试用try catch

try:
    int(c)
except ValueError:
    pass

Time Complexity - O(n),  Space Complexity - O(1)

class Solution(object):
    max_value = 2147483647
    min_value = -2147483648
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if str == None or len(str) == 0:
            return 0
        index = 0
        while str[index] == ' ':
            index += 1
        sign = 1
        if str[index] in ('+', '-'):
            if str[index] == '-':
                sign = -1
            index += 1
        res = 0    
        while index < len(str):
            c = str[index]
            num = 0
            if c.isdigit():
                num = int(c)
                if res > self.max_value / 10:
                    return self.max_value if sign == 1 else self.min_value
                elif res == self.max_value / 10:
                    if sign == -1 and num > 8:
                        return self.min_value
                    elif sign == 1 and num > 7:
                        return self.max_value
                res = res * 10 + num
            else:
                return res * sign
            index += 1
        return res * sign
        

 

测试:

1. "+-2"

2. "    123  456"

3. "      -11919730356x"

4. "2147483647"

5. "-2147483648"

6. "2147483648"

7. "-2147483649"

二刷:

Time Complexity - O(n), Space Complexity - O(1)

Java: 二刷思路就比较清晰。依然是有下面几个步骤:

  1. 判断str是否为空或者长度是否为0
  2. 处理前部的space,也可以用str = str.trim();
  3. 尝试求出符号sign
  4. 定义结果int res = 0 ,  处理数字
    1. 假如char c = str.charAt(index)是数字,则定义int num = c - '0', 接下来判断是否越界
      1. 当前 res > Integer.MAX_VALUE / 10,越界,根据sign 返回 Integer.MAX_VALUE或者 Integer.MIN_VALUE
      2. res == Integer.MAX_VALUE / 10时, 根据最后sign和最后一位数字来决定是否越界,返回Integer.MAX_VALUE或者 Integer.MIN_VALUE
      3. 不越界情况下,res = res * 10 + num
    2. 否则返回当前 res * sign
  5. 返回结果 res * sign

这里比较tricky的点是,从Integer.MAX_VALUE和Integer.MIN_VALUE越界时要分别返回Integer.MAX_VALUE或者Integer.MIN_VALUE。假如当前字符不为数字,则返回之前已经计算过的,到这一位为止的res * sign。

public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        int index = 0;
        while (str.charAt(index) == ' ') {
            index++;
        }
        int sign = 1;
        if (str.charAt(index) == '+' || str.charAt(index) == '-') {
            if (str.charAt(index) == '-') {
                sign = -1;
            }
            index++;
        }
        
        int res = 0;
        while (index < str.length()) {
            char c = str.charAt(index);
            if (c >= '0' && c <= '9') {
                int num = c - '0';
                if (res > Integer.MAX_VALUE / 10) {
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                } else if (res == Integer.MAX_VALUE / 10) {
                    if (sign == -1 && num > 8) {
                        return Integer.MIN_VALUE;
                    } else if (sign == 1 && num > 7) {
                        return Integer.MAX_VALUE;
                    }
                }  
                res = res * 10 + num;
            } else {
                return res * sign;
            }
            index++;
        }
        
        return res * sign;
    }
}

三刷:

写多了也就顺了。还是要多写

Java:

Time Complexity - O(n),  Space Complexity - O(1)

public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        str = str.trim();
        int index = 0;
        boolean isNeg = false;
        if (str.charAt(index) == '-') {
            isNeg = true;
            index++;
        } else if (str.charAt(index) == '+') {
            index++;
        }
        int res = 0;
        while (index < str.length()) {
            char c = str.charAt(index);
            if (c > '9' || c < '0') return isNeg ? -res : res;
            if (res > Integer.MAX_VALUE / 10) {
                return isNeg ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            } else if (res == Integer.MAX_VALUE / 10) {
                if (isNeg && (c - '0') > 8) return Integer.MIN_VALUE;
                else if (!isNeg && (c - '0') > 7) return Integer.MAX_VALUE;
            }
            res = res * 10 + c - '0';
            index++;
        }
        return isNeg ? -res : res;
    }
}

Python:

Reference:

原文地址:https://www.cnblogs.com/yrbbest/p/4430375.html