Leetcode_8. String to Integer (atoi) 字符串转化为整数(空格、正负号、数字、字符串等的处理)

题目:

Implement atoi which converts a string to an integer.

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.

Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

 

代码:

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        
        str = str.strip()        #先去掉可能存在的空格,防止全是空格,后面判断符号的时候取下标会溢出  strip():去掉字符串首尾的空格
        
        if str == "" :
            return 0
        
        sign = 1     #默认为正数
        
        if str[0] == '-' :    #判断是否为负数
            sign = -1

        if str[0] in "-+" :   #去掉字符串前面的符号
            str = str[1:]

        result = 0
        for x in str :
            if x <= '9' and x >= '0' :
                result = result*10 + int(x)
            else :
                break

        return max(-2147483648, min(sign*result, 2147483647))              

题目描述: 请你来实现一个 atoi 函数,使其能将字符串转换成整数。该函数需要丢弃无用的开头空格,找到第一个非空格字符,然后将其后面的字符(如果符合要求的话)转换成整数,如果第一个非空字符为正或者负号时,将该符号与后面尽可能多的连续数字组合起来,返回整数。如果第一个非空字符是非数字字符或者一开始没有给定任何数字,则返回 0。 注意: 假如只能存储有限的整数范围内,例如32位整数,则请返回 INT_MAX(231 − 1)或 INT_MIN(−231)。 示例: 输入: "42" 输出: 42 输入: " -42" 输出: -42 解释: 第一个非空白字符为 '-', 它是一个负号。我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 输入: "4193 with words" 输出: 4193 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 输入: "words and 987" 输出: 0 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。因此无法执行有效的转换。 输入: "-91283472332" 输出: -2147483648 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。因此返回 INT_MIN(−231)。 解题思路: 这道题比较繁琐,需要注意的地方很多,需要仔细考虑每一种情况。下面是一种比较清晰的思路: 1. 删除字符串前面的空格。 2. 判断第一个非空字符是否为正负号数字,如果是数字则开始转换,否则直接返回0。 3. 转换过程中如果遇到非数字字符,则停止转换,返回当前已转换的数字。 4. 判断转换后的数字是否超出了32位有符号整数的范围,如果超出了则返回对应的极值。 代码实现: ```python class Solution: def myAtoi(self, str: str) -> int: # 删除字符串前面的空格 str = str.lstrip() # 判断第一个非空字符是否为正负号数字 if not str or (not str[0].isdigit() and str[0] not in ['+', '-']): return 0 # 转换过程中如果遇到非数字字符,则停止转换 i = 1 while i < len(str) and str[i].isdigit(): i += 1 # 转换数字 num_str = str[:i] sign = -1 if num_str[0] == '-' else 1 num = 0 for c in num_str: if c.isdigit(): num = num * 10 + int(c) else: break # 判断转换后的数字是否超出了32位有符号整数的范围 max_int = 2**31 - 1 min_int = -2**31 num = num * sign if num > max_int: return max_int elif num < min_int: return min_int else: return num ``` 时间复杂度:$O(n)$,其中 $n$ 是字符串的长度。需要对字符串进行一次遍历。 空间复杂度:$O(1)$。除了常量空间之外,不需要额外的空间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值