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

1,问题描述

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

难度:中等

请你来实现一个 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
2
3
4
5
6
7
带下划线线的字符是所读的内容,插入符号是当前读入位置。
第 1 步:"42"(当前没有读入字符,因为没有前导空格)
^
第 2 步:"42"(当前没有读入字符,因为这里不存在 '-' 或者 '+')
^
第 3 步:"42"(读入 "42")
^

示例 2:

**输入:**s = “ -042”

输出:-42

解释:

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

示例 3:

**输入:**s = “1337c0d3”

**输出:**1337

解释:

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

示例 4:

**输入:**s = “0-1”

**输出:**0

解释:

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

示例 5:

**输入:**s = “words and 987”

**输出:**0

解释:

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

提示:

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

2,初步思考

​ 解法1:有限状态机,利用java的异常处理

​ 解法2:按阶段处理,第一阶段处理先导空格、下一阶段处理符号、下一阶段处理数字等等

3,代码处理

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class _8字符串转换整数atoi {

// 解法:指针
public int myAtoi(String str) {
int len = str.length();
char[] charArray = str.toCharArray();
int idx = 0;
while (idx < len && charArray[idx] == ' ') {
idx++;
}// 1,去除前导空格

// 2、如果已经遍历完成(针对极端用例 " ")
if (idx == len) {
return 0;
}

// 3、如果出现符号字符,仅第 1 个有效,并记录正负
int sign = 1;
char firstChar = charArray[idx];
if (firstChar == '+') {
idx++;
} else if (firstChar == '-') {
idx++;
sign = -1;
}

// 4、将后续出现的数字字符进行转换
// 不能使用 long 类型,这是题目说的
int res = 0;
while (idx < len) {
char currChar = charArray[idx];
// 4.1 先判断不合法的情况
if (currChar > '9' || currChar < '0') {
break;
}

// 题目中说:环境只能存储 32 位大小的有符号整数,因此,需要提前判:断乘以 10 以后是否越界
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
return Integer.MAX_VALUE;
}
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
return Integer.MIN_VALUE;
}

// 4.2 合法的情况下,才考虑转换,每一步都把符号位乘进去
res = res * 10 + sign * (currChar - '0');
idx++;
}
return res;
}

// 解法:有限状态机
public int myAtoi_svm(String s) {
int status = 0;// 0初始化,1空格,2符号,3数字,4其他
int sum = 0;
int sign = 1;
StringBuilder sbTemp = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == ' ') {// 空格
if (status > 1) {
break;
}
status = 1;
continue;
} else if (c <= '9' && c >= '0') {// 数字
status = 2;
if (sbTemp.isEmpty() && c == '0') continue;
sbTemp.append(c);
} else if (c == '+' || c == '-') {// 符号
if (status > 1) {
break;
}
sign = c == '+' ? 1 : -1;// 更新正负符号。默认为正
status = 2;
} else {// 其他字符,直接停止
status = 3;
break;
}
}
if (sbTemp.isEmpty()) return 0;
sbTemp.insert(0, sign == 1 ? "" : "-");
try {
sum = Integer.parseInt(sbTemp.toString());
} catch (Exception e) {
if (sign == 1) {
sum = Integer.MAX_VALUE;
} else {
sum = Integer.MIN_VALUE;
}
}
return sum;
}

public static void main(String[] args) {
_8字符串转换整数atoi atoi = new _8字符串转换整数atoi();
// System.out.println(atoi.myAtoi("-91283472332"));
// System.out.println(atoi.myAtoi("0-1"));
// System.out.println(atoi.myAtoi(" +0 123"));
System.out.println(atoi.myAtoi("+-12"));
}

}