String to Integer (atoi)


2018-05-19 18:12:59 by sikoay with 0 comments 1 Hits
Blog 1

字符串转整数

没什么想法!简单!


class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        strlen = len(str)
        i = 0
        result = 0
        while i < strlen:
            if str[i] == '-':
                result = -int(self.numstrjoin(str,i+1))
                break
            if str[i] == '+':
                result = int(self.numstrjoin(str,i+1))
                break
            elif str[i] in string.digits:
                result = int(self.numstrjoin(str,i))
                break
            elif str[i] == ' ':
                i += 1
            else:
                break
        if result > 2147483647:
            return 2147483647
        elif result < -2147483648:
            return -2147483648
        return result
                
                
    def numstrjoin(self,str,num):
        result = ''
        strlen = len(str)
        while True:
            if num<strlen and str[num] in string.digits:
                result += str[num]
            else:
                break
            num += 1
        if len(result) ==0:
            return '0'
        return result



Tags:

回复 (0)

Leave a Comment