String to Integer (atoi)解题报告

来源:互联网 发布:多系统数据同步 编辑:程序博客网 时间:2024/06/10 01:24

感觉string的题目在leetcde中都比较靠前,是不是因为是最早出的,所以题目的表述都有一些简略,很多时候看不懂题orz。

题目描述

Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

解题思路

这道题就是要考虑一些特殊的情况:

1 去除空格

2 数字前出现多余的字符

3 数字中有空格或非数字字符

4 越界

代码

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        if len(str)==0:            return 0        str=str.strip()        isP=False        isN=False        has=False        for i in range(len(str)):            if str[i]=='+':                isP=True                has=True            if str[i]=='-':                isN=True                has=True        if has:            if isP and isN:                return 0        if has:            str=str[1:]        i=0        while i<len(str) and ord(str[i]) in range(48,58):            i+=1        r=0        if i>0:            r=int(str[:i])        if isN:            r*=-1        return max(min(r,pow(2,31)-1),-pow(2,31))

0 0
原创粉丝点击