码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]8. String to Integer (atoi)

时间:2019-05-03 13:03:55      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:函数   only   git   span   time   white   style   tail   hit   

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

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

 

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

 

[leetcode]8. String to Integer (atoi)

标签:函数   only   git   span   time   white   style   tail   hit   

原文地址:https://www.cnblogs.com/alfredsun/p/10804801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!