moonlightshadow123
6/19/2017 - 10:23 AM

8. String to Integer (atoi)

  1. String to Integer (atoi)
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = str.strip()
        if str == '':
            return 0
        i = 0
        while ord(str[i]) == ord('-') or ord(str[i]) == ord('+') or \
              (ord('0') <= ord(str[i]) and ord(str[i]) <= ord('9')):
            i += 1
            if i == len(str):
                break
        str = str[:i]
        print str
        try:
            val = int(str)
            if val > 0x7fffffff:
                return 0x7fffffff
            elif val < -0x80000000:
                return -0x80000000
            else:
                return val
        except:
            return 0

https://leetcode.com/problems/string-to-integer-atoi/#/description

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.