【LeetCode with Python】 String to Integer (atoi)

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/string-to-integer-atoi/
题目类型:字符串处理
难度评价:★★★
本文地址: http://blog.csdn.net/nerv3x3/article/details/3465509

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.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

spoilers alert... click to show requirements for atoi.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.


一、正负号自然不用说,还要注意字符串开头允许任意长度的空格,结尾允许任意长度的非数字字符。
二、int为32位数据类型,当字符串代表的整数值超出int的表示范围时(大于int最大值,或小于int最小值),要能截断到int的最大值或最小值。但是如何判断当前的值已经大于int最大值或者小于int最小值,此时如果用int存储当前值的话,已经发生溢出而出错。当然,这里是用Python来解题的,整数变量的范围不止32位。但是如果是用C++结题呢?一般两种做法,一个是用更大的数据类型,如long long来存储当前值。还有一种办法,就是类似于下面的代码中的方法,就是直接用当前值的字符串,和int最大值最小值的字符串去进行字符串大小比较。


class Solution:

    def __init__(self):
        self.max_int_bits = 32
        self.max_int_str = str(pow(2, self.max_int_bits - 1) - 1)
        self.min_int_str = str(pow(2, self.max_int_bits - 1))   # abs value, without sign
        self.max_int_len = len(self.max_int_str)
        self.min_int_len = len(self.min_int_str)

    # @return an integer
    def atoi(self, str):

        len_s = len(str)
        if 0 == len_s:
            return 0

        index = 0
        while index < len_s and ' ' == str[index]:
            index += 1
        sign = 1
        if index < len_s:
            if '+' == str[index]:
                sign = 1
                index += 1
            elif '-' == str[index]:
                sign = -1
                index += 1
        value = 0
        val_str = ''
        for i in range(index, len_s):
            ch = str[i]
            if ch >= '0' and ch <= '9':
                val_str += ch

                if len(val_str) > self.max_int_len or len(val_str) > self.min_int_len:
                    return int(self.max_int_str) if 1 == sign else -int(self.min_int_str)
                if len(val_str) >= self.max_int_len and val_str > self.max_int_str:
                    return int(self.max_int_str) if 1 == sign else -int(self.min_int_str)

                value = value * 10 + ord(ch) - ord('0')
                index += 1
            else:
                break

        return value * sign

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值