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.

Solution:

MAX_INT = 2147483647
MIN_INT = -2147483648


class Solution(object):
    def myAtoi(self, s):
        """
        :type s: str
        :rtype: int
        """
        i = 0
        while i < len(s) and s[i] == ' ':
            i += 1

        is_negative = False
        if i < len(s) and s[i] in '+-':
            is_negative = s[i] == '-'
            i += 1

        num = 0
        while i < len(s) and s[i].isdigit():
            num = num * 10 + ord(s[i]) - ord('0')
            if num > MAX_INT:
                return MIN_INT if is_negative else MAX_INT
            i += 1
        return -num if is_negative else num

results matching ""

    No results matching ""