按规则将字符串转换为整形

Python解决方案:

  

    def myAtoi(self, s):
        """
        :type str: s
        :rtype: int
        """
        s = s.lstrip()
        if not s:
            return 0
        
        header = s[0]
        length = len(s)
                
        if header.isnumeric():
            out = ""
            i = 0
            while i < len(s) and s[i].isnumeric():
                out += s[i]
                i += 1  
            return int(out)
        elif header in ["+","-"]:
            if length == 1:
                return 0
            else:
                if not s[1].isnumeric():
                    return 0
                out = header
                i = 1
                while i < len(s) and s[i].isnumeric():
                    out += s[i]
                    i += 1
                return int(out)
        else:
            return 0

 

posted @ 2019-03-15 11:26  秦qin  阅读(192)  评论(0编辑  收藏  举报