老卫带你学---剑指offer刷题系列(49.把字符串转换成整数)

49.把字符串转换成整数

问题:

将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0

解决:

思想:

这道要注意一下,32位整数的范围在-2**31到2*32-1。

python代码:

# -*- coding:utf-8 -*-
class Solution:
    def StrToInt(self, s):
        try:
            a=int(s)
            if(a<-(2**31) or a>(2**31-1)):
                return 0
            return a
        except Exception as e:
            return 0
发布了160 篇原创文章 · 获赞 30 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yixieling4397/article/details/105069254