【Leetcode】【python】String to Integer (atoi)

来源:互联网 发布:新手开淘宝店卖什么好 编辑:程序博客网 时间:2024/05/29 07:08

题目大意

写出函数,将str转为int
需要考虑所有可能的输入情况

解题思路

将情况都考虑进去

代码

class Solution(object):    def myAtoi(self, str):        """        :type str: str        :rtype: int        """        INT_MAX =  2147483647        INT_MIN = -2147483648        result = 0        if not str:  # 不是str返回0            return result        i = 0        while i < len(str) and str[i].isspace():  # 判断空格            i += 1        sign = 1  # 若有‘-’结果相反数        if str[i] == "+":            i += 1        elif str[i] == "-":            sign = -1            i += 1        while i < len(str) and str[i] >= '0' and str[i] <= '9':            if result > (INT_MAX - (ord(str[i]) - ord('0'))) / 10:                return INT_MAX if sign > 0 else INT_MIN            result = result * 10 + ord(str[i]) - ord('0')            i += 1        return sign * result

总结

这里用ord()计算ascii的差值,如果直接int()那就等于把这题直接用内部函数解决了。

原创粉丝点击