LeetCode 8. 字符串转换整数 (atoi)

题目描述

8. 字符串转换整数 (atoi)

image-20250419022104874

思路分析

image-20250508003515824

image-20250510100242729

参考代码

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
30
31
32
33
34
35
36
37
func myAtoi(s string) int {
	var res int
	var sign int = 1
	i := 0

	// 1. 去除前导空格
	for i < len(s) && s[i] == ' ' {
		i++
	}

	// 2. 判断符号
	if i < len(s) && (s[i] == '+' || s[i] == '-') {
		if s[i] == '-' {
			sign = -1
		}
		i++
	}

	// 3. 转换数字
	for i < len(s) && s[i] >= '0' && s[i] <= '9' {
		digit := int(s[i] - '0')
		res = res*10 + digit
		i++

		// 处理溢出
		if res > (1<<31)-1 {
			if sign == 1 {
				return (1 << 31) - 1
			} else {
				return -(1 << 31)
			}
		}
	}

	// 4. 返回最终结果
	return res * sign
}
  • 时间复杂度:O(n),其中 n 为字符串的长度。
  • 空间复杂度:O(1),只用了常数级别的额外空间。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/71927843
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!