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.

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.

Solution

(1) Java

A few corner cases(a)overflow integer(b)123c45->123(c)+/-

public int myAtoi(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        str = str.trim();
        int sign = 1;
        if (str.charAt(0) == '-') {
            sign = -1;
            str = str.substring(1);
        } else if (str.charAt(0) == '+') {
            str = str.substring(1);
        }
        int rst = 0;
        char[] chars = str.toCharArray();
        for (char c : chars) {
            if (c < '0' || c > '9') {
                return sign*rst;
            }
            if (Integer.MAX_VALUE/10 < rst || (Integer.MAX_VALUE/10 == rst && Integer.MAX_VALUE%10 < c-'0' )) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            rst = rst*10+c-'0';

        }
        return sign*(int)rst;
    }

(2) Python

    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if not str:
            return 0
        str = str.strip()
        sign = 1
        if str[0] == '-':
            sign = -1
        if str[0] == '-' or str[0] == '+':
            str = str[1::]
        rst = 0
        for i in xrange(len(str)):
            if ord(str[i])>=ord('0') and ord(str[i])<=ord('9'):
                rst = rst*10+ord(str[i])-ord('0')
            else:
                return sign*rst
            if rst > 2**31-1:
                return 2**31-1 if sign == 1 else -2**31
        return sign*rst

(3) Scala

object Solution {
    def myAtoi(str: String): Int = {
        var str1 = str.trim()
        if (str1.length() < 1) {
            return 0
        }
        val sign = str1(0) match {
            case '-' => str1 = str1.substring(1); -1
            case '+' => str1 = str1.substring(1); 1
            case _ => 1
        }
        var rst = 0
        for (i <- 0 until str1.length()) {
            if (str1(i) < '0' || str1(i) > '9') {
                return rst*sign
            }
            if (Int.MaxValue/10 < rst || (Int.MaxValue/10 == rst && Int.MaxValue%10 < str1(i)-'0')) {
                return if (sign == 1) Int.MaxValue else Int.MinValue
            }
            rst = rst*10 + str1(i)-'0'
        }
        return sign*rst
    }
}

results matching ""

    No results matching ""