美文网首页
LintCode_chapter1_section7_strin

LintCode_chapter1_section7_strin

作者: 穆弋 | 来源:发表于2015-11-06 16:45 被阅读60次

coding = utf-8

'''
Created on 2015年11月6日

@author: SphinxW
'''
# 转换字符串到整数
#
# 实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。
# 样例
#
# "10" =>10
#
# "-1" => -1
#
# "123123123123123" => 2147483647
#
# "1.0" => 1


class Solution:
    # @param str: a string
    # @return an integer

    def atoi(self, str):
        # write your code here
        res = ""
        numMode = False
        for index, item in enumerate(str):
            if numMode:
                if item not in ".0123456789":
                    break
                if item in ".-+0123456789":
                    res = res + item
            else:
                if item in ".-+0123456789":
                    res = res + item
                    numMode = True
        print(res)
        try:
            intStr = int(float(res))
        except ValueError:
            return 0
        if intStr > 2147483647:
            return 2147483647
        if intStr < -2147483648:
            return -2147483648
        return intStr
s = Solution()
print(s.atoi("0"))

相关文章

网友评论

      本文标题:LintCode_chapter1_section7_strin

      本文链接:https://www.haomeiwen.com/subject/lbschttx.html