LeetCode--String to Integer (atoi)字符串转数字

来源:互联网 发布:淘宝网店实践总结报告 编辑:程序博客网 时间:2024/05/16 07:48

题目:

给定字符串,将其转为int型并输出。像c++中的atoi函数一样

解题思路:

本题比较简单,需要考虑的是各种字符串转为int型可能出现的各种特殊情况。如“123    456”的输出结果为123; “+0    123”输出结果为0; “+-1”的输出结果为0; 当数字超过2147483647 或者小于-2147483648时,分别返回这两个值即可。

本题只要注意到所有可能出现的特殊情况并加以处理,就可以AC

代码如下(python):

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        if len(str) == 0:            return 0        flag = 0        output = 0        sign = 1        for i in str:            if i=='+' and flag==0:                sign = 1                flag = i                continue            if i=='-' and flag==0:                sign = -1                flag = i                continue            if i >= '0' and i<='9':                output = output*10+int(i)                continue            if i==" " and flag==0 and output==0:                continue            else:                break        temp = output*sign        if temp>2147483647:            return 2147483647        if temp<-2147483648:            return -2147483648        return temp


原创粉丝点击