[leetcode 008] 字符串转换整数

实现一个能将字符串转换成整数的函数。

示例:

输入:"42"

输出:42

 

输入:“   -42”

输出:-42

 

输入:"words with 987"

输出:0

 

代码:

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        sign = 1
        max_int, min_int = 2147483647, -2147483648
        result, pos = 0, 0
        ls = len(str)

        while pos < ls and str[pos] == ' ':
            pos += 1
          if pos < ls and str[pos] == '-':
              sign = -1
              pos += 1
          elif pos < ls and str[pos] == '+':
              pos += 1

        while pos < ls and ord(str[pos]) >= ord('0') and ord(str[pos]) <= ord('9'):
            num = ord(str[pos]) - ord('0')

            if result > max_int / 10 or ( result == max_int / 10 and num >= 8):
                if sign == -1:
                    return min_int
                return max_int
            result = result * 10 + num
            pos += 1
        return sign * result

参考链接:https://github.com/qiyuangong/leetcode/blob/master/python/008_String_to_Integer(atoi).py

转载于:https://www.cnblogs.com/statlearning2019/p/10340329.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值