String to Integer (atoi)

Problem: String to Integer (atoi)

The general idea is to read one digit for one time and construct an integer. There are integer details about INT_MAX and INT_MIN. Besides, we need to notice that illegal symbol can end conversion. We use an flag called "signed" to judge whether there are redundant positive or negative symbols.

Code in Python:

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        pos, ans, signed = 1, 0, False
        for c in str:
            if c in string.digits:
                if not signed:
                    signed = True
                ans = ans * 10 + int(c)
                if pos > 0 and ans > 2147483647:
                    return 2147483647
                if pos < 0 and ans > 2147483648:
                    return -2147483648
            elif not signed:
                if c == "-":
                    signed, pos = True, -1
                elif c == "+":
                    signed = True
                elif c != " ":
                    break
            else:
                break
        return pos * ans

Code in Java:

public class Solution {
    public int myAtoi(String str) {
        if (str == null || str.length() == 0) return 0;
        str = str.trim();
        char first = str.charAt(0);
        int sign = 1, start = 0, n = str.length();
        long result = 0;
        if (first == '+') {
            sign = 1;
            start++;
        } else if (first == '-') {
            sign = -1;
            start++;
        }
        for (int i = start; i < n; i++) {
            if (!Character.isDigit(str.charAt(i))) return (int) result * sign;
            result = result * 10 + str.charAt(i) - '0';
            if (sign == 1 && result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (sign == -1 && (-1) * result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        }

        return (int) result * sign;
    }
}

results matching ""

    No results matching ""