LeetCode 题解工作台

字符串转换整数 (atoi)

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。 函数 myAtoi(string s) 的算法如下: 空格: 读入字符串并丢弃无用的前导空格( " " ) 符号: 检查下一个字符(假设还未到字符末尾)为 '-' 还是 '+' 。如果两者都不存在…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · String-driven solution strategy

bolt

答案摘要

我们首先判断字符串是否为空,如果是,直接返回 。 否则,我们需要遍历字符串,跳过前导空格,判断第一个非空格字符是否为正负号。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数。

函数 myAtoi(string s) 的算法如下:

  1. 空格:读入字符串并丢弃无用的前导空格(" "
  2. 符号:检查下一个字符(假设还未到字符末尾)为 '-' 还是 '+'。如果两者都不存在,则假定结果为正。
  3. 转换:通过跳过前置零来读取该整数,直到遇到非数字字符或到达字符串的结尾。如果没有读取数字,则结果为0。
  4. 舍入:如果整数数超过 32 位有符号整数范围 [−231,  231 − 1] ,需要截断这个整数,使其保持在这个范围内。具体来说,小于 −231 的整数应该被舍入为 −231 ,大于 231 − 1 的整数应该被舍入为 231 − 1

返回整数作为最终结果。

 

示例 1:

输入:s = "42"

输出:42

解释:加粗的字符串为已经读入的字符,插入符号是当前读取的字符。

带下划线线的字符是所读的内容,插入符号是当前读入位置。
第 1 步:"42"(当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"42"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"42"(读入 "42")
           ^

示例 2:

输入:s = " -042"

输出:-42

解释:

第 1 步:"   -042"(读入前导空格,但忽视掉)
            ^
第 2 步:"   -042"(读入 '-' 字符,所以结果应该是负数)
             ^
第 3 步:"   -042"(读入 "042",在结果中忽略前导零)
               ^

示例 3:

输入:s = "1337c0d3"

输出:1337

解释:

第 1 步:"1337c0d3"(当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"1337c0d3"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"1337c0d3"(读入 "1337";由于下一个字符不是一个数字,所以读入停止)
             ^

示例 4:

输入:s = "0-1"

输出:0

解释:

第 1 步:"0-1" (当前没有读入字符,因为没有前导空格)
         ^
第 2 步:"0-1" (当前没有读入字符,因为这里不存在 '-' 或者 '+')
         ^
第 3 步:"0-1" (读入 "0";由于下一个字符不是一个数字,所以读入停止)
          ^

示例 5:

输入:s = "words and 987"

输出:0

解释:

读取在第一个非数字字符“w”处停止。

 

提示:

  • 0 <= s.length <= 200
  • s 由英文字母(大写和小写)、数字(0-9)、' ''+''-''.' 组成
lightbulb

解题思路

方法一:遍历字符串

我们首先判断字符串是否为空,如果是,直接返回 00

否则,我们需要遍历字符串,跳过前导空格,判断第一个非空格字符是否为正负号。

接着遍历后面的字符,如果是数字,我们判断添加该数字是否会导致整数溢出,如果会,我们根据正负号返回结果。否则我们将数字添加到结果中。继续遍历后面的字符,直到遇到非数字字符或者遍历结束。

遍历结束后,我们根据正负号返回结果。

时间复杂度 O(n)O(n),其中 nn 为字符串的长度。我们只需要依次处理所有字符。空间复杂度 O(1)O(1)

面试题 67. 把字符串转换成整数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    def myAtoi(self, s: str) -> int:
        if not s:
            return 0
        n = len(s)
        if n == 0:
            return 0
        i = 0
        while s[i] == ' ':
            i += 1
            # 仅包含空格
            if i == n:
                return 0
        sign = -1 if s[i] == '-' else 1
        if s[i] in ['-', '+']:
            i += 1
        res, flag = 0, (2**31 - 1) // 10
        while i < n:
            # 非数字,跳出循环体
            if not s[i].isdigit():
                break
            c = int(s[i])
            # 溢出判断
            if res > flag or (res == flag and c > 7):
                return 2**31 - 1 if sign > 0 else -(2**31)
            res = res * 10 + c
            i += 1
        return sign * res
speed

复杂度分析

指标
时间complexity is O(n) where n is the length of the string, because each character is processed at most once. Space complexity is O(1) as only a few integer variables are maintained, regardless of input length.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Clarifies how whitespace and signs are handled before digit accumulation.

  • question_mark

    Asks about integer overflow behavior when parsing large numeric strings.

  • question_mark

    Checks handling of non-digit characters following the numeric portion.

warning

常见陷阱

外企场景
  • error

    Failing to skip leading spaces before detecting the sign.

  • error

    Ignoring overflow cases, which can produce incorrect or runtime errors.

  • error

    Incorrectly processing strings with no valid digits, leading to non-zero returns.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Converting strings with different numeric bases such as hexadecimal or binary.

  • arrow_right_alt

    Handling floating-point numbers by extending parsing to decimals.

  • arrow_right_alt

    Parsing strings with embedded commas or formatting characters into integers.

help

常见问题

外企场景

字符串转换整数 (atoi)题解:String-driven solution … | LeetCode #8 中等