[leetcode]8. String to Integer (atoi)

分 空白 无符号 正号 负号 无意义符号分别讨论:

有点难看 应该写成函数分开的

 

Submission Detail

1079 / 1079 test cases passed. Status: 

Accepted

Runtime: 44 ms Memory Usage: 13.3 MB Submitted: 1 minute ago

 

class Solution:
    def myAtoi(self, str: str) -> int:
        # 00  -(+) nums
        strS = len(str)
        # deal 0
        if strS == 0:  # str is empty
            return 0
        #noraml
        maxnum = 0x80000000
        for index in range(strS):
            if str[index] == ' ':  # whitespace character
                continue
            else:
                # min
                if str[index] == '-':
                    if index + 1 < strS:
                        ret = ''
                        for i in range(index + 1, strS):
                            if str[i].isdigit():
                                ret = ret + str[i]
                            else:
                                break
                        if ret == '-' or len(ret) == 0:
                            return 0
                        if int(ret) <= maxnum:
                            return int('-' + ret)
                        else:
                            ret =0
                            ret = ret - maxnum
                            return int(ret)
                #plus
                if str[index] == '+':
                    if index + 1 < strS:
                        ret = ''
                        for i in range(index + 1, strS):
                            if str[i].isdigit():
                                ret = ret + str[i]
                            else:
                                break
                        if ret == '+' or len(ret) == 0:
                            return 0
                        if int(ret) <= maxnum:
                            return int(ret)
                        else:
                            ret =0
                            ret = maxnum -1
                            return int(ret)
                # nosign or nomean
                if (str[index].isdigit()):
                    ret = ''
                    for i in range(index, strS):
                        if str[i].isdigit():
                            ret = ret + str[i]
                        else:
                            break
                    if (int(ret)<=maxnum-1):
                        return int(ret)
                    else:
                        ret = maxnum - 1
                        return int(ret)
                else:
                    return 0
        #only one blankchar
        return 0

 

上一篇:Windows 10安装cacti


下一篇:常见的监控软件及特点