Leetcode8_String to Integer (atoi)

来源:互联网 发布:java main启动 编辑:程序博客网 时间:2024/05/29 09:51

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.“`

python代码

我的解题代码:

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        # !!!!最开始没有想到这种情况        if str == '':            return 0        # 控制正负        positive = 1        lenstr = len(str)        # 需要初始化sum和k        sum = 0        k = 0        # 如果为空格就舍去,直到出现有字符的一项        for i in range(lenstr):            if str[i] != ' ':                k = i                break        str = str[k:]        # 判断如果第一个符号是+或-,则从第二个字符开始取数字部分        if str[0] == '-':            positive = -1;            str = str[1:]        elif str[0] == '+':            str = str[1:]        #print (str)        for i in str:            # ord函数将字符转化成ascii的值,比如ord('0')=48            if (ord(i) >= ord('0') ) and (ord(i) <= ord('9')):                sum = sum * 10 + (ord(i) - ord('0'))                #提交时没有考虑到下面的情况                if positive ==1 and sum >= 2147483647:                    return 2147483647                if positive == -1 and sum >= 2147483648:                    return -2147483648            else:                break        sum *= positive        return sum# f = Solution()# str = '             -012a3'# print(f.myAtoi(str))

参考答案:

class Solution:    # @return an integer    def atoi(self, str):        str = str.strip()        #原答案str = re.findall('(^[\+\-0]*\d+)\D*', str)        #简化,还需要学习正则化        str = re.findall('^[+\-]?\d+', str)        try:            #这一步int就好使。白费我各种x10            result = int(''.join(str))            MAX_INT = 2147483647            MIN_INT = -2147483648            if result > MAX_INT > 0:                return MAX_INT            elif result < MIN_INT < 0:                return MIN_INT            else:                return result        except:            return 0
解析:
  • strip()函数
    • s.strip(rm) 删除s字符串开头、结尾处,位于rm删除序列的字符
    • s.lstrip(rm) 删除s字符串开头处,位于 rm删除序列的字符
    • s.rstrip(rm) 删除s字符串结尾处,位于 rm删除序列的字符
>>>str = '      - a0 bb   '>>>strstrip = str.strip()>>>strstrip
`>>>'- a0 bb'`
  • 正则表达式推荐几个好的博客,连着看:
    正则表达式简单教程;
    正则表达式简单教程;
    正则表达式简表;
    可以到正则表达式在线测试测试。还是很好理解的。