LintCode_chapter1_section7_string-to-integeratoi

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"))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容