leetcode--8. String to Integer (atoi)

来源:互联网 发布:js传值到html 编辑:程序博客网 时间:2024/06/15 23:25

题目:8. String to Integer (atoi)

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

将给定的字符串转为整数。需要考虑一些特殊的输入情况,比如前导空格要忽略正负号不忽略,要转换到最开始的非数字字符等。具体有哪些坑在题目下面列出了一部分,其他的瞎改通过了。

python:

class Solution(object):    def myAtoi(self, string):        """        :type str: str        :rtype: int        """        if not string:            return 0        s = ""        start = 0        while string[start] == ' ':            start += 1        s = string[start:len(string)]        start = end = 0        if len(s) == 1:            if s[0] < '0' or s[0] > '9':                return 0            else:                return int(s)        if (s[0]<'0' or s[0]>'9') and s[0]!='+' and s[0]!='-':            return 0        if (s[1] < '0' or s[1] > '9'):            if (s[0]>='0' and s[0]<='9'):                return int(s[0])            else:                return 0         while s[start] < '0' or s[start] > '9':            start += 1            if start >= len(s):                return 0        end = start        while s[end] >= '0' and s[end] <= '9':            end += 1            if end >= len(s):                break        res = 0        if s[0] == '-':            res = -int(s[start:end])        else:            res = int(s[start:end])        # res=int(s[start:end]) if s[0]=='+' else -int(s[start:end])        if res >= -0x80000000 and res <= 0x7fffffff:            return res        else:            return 0x7fffffff if res > 0 else -0x80000000