把字符串转换成整数 (atoi)
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 44 ms, 内存: 14.8 MB
/*
* Approach using Java Streams:
* 1. Discard leading whitespace characters.
* 2. Use Streams to process the string and convert to integer.
* 3. Handle sign and overflow conditions.
*/
import java.util.stream.IntStream;
public class SolutionStream {
public int myAtoi(String s) {
int[] result = {0}; // Using an array to capture result inside lambda
int[] sign = {1};
boolean[] started = {false};
// Using Streams to iterate characters
IntStream.range(0, s.length()).forEach(i -> {
char c = s.charAt(i);
if (!started[0] && c == ' ') return;
if (!started[0] && (c == '+' || c == '-')) {
sign[0] = c == '-' ? -1 : 1;
started[0] = true;
return;
}
if (Character.isDigit(c)) {
started[0] = true;
int digit = c - '0';
if (result[0] > (Integer.MAX_VALUE - digit) / 10) {
result[0] = sign[0] == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
return;
}
result[0] = result[0] * 10 + digit;
} else if (started[0]) {
return;
}
});
return result[0] * sign[0];
}
}
解释
方法:
该题解首先使用strip()去除字符串s的前导和后续空格。若处理后的字符串为空,则直接返回0。接下来,判断字符串首字符是否为正负号,以确定结果的符号并设置起始索引。然后,初始化结果变量res为0,并设置一个界限值boundary,用于判断结果是否溢出。遍历字符串中的字符,如果字符是数字,则计算其整数值并更新结果res;如果遇到非数字字符或者结果溢出,则停止遍历。最后,根据符号变量sign调整res的符号,并返回最终结果。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在`myAtoi`函数中,你是如何确定何时停止读取数字,并处理非数字字符的?
▷🦆
函数中使用`strip()`来移除字符串的前导和后续空格,但如果输入字符串含有中间空格怎么处理?
▷🦆
在处理数字溢出时,你设置的边界值`boundary`为`(2**31-1) // 10`,能具体解释为什么选择这个值作为边界吗?
▷🦆
在判断字符是否为数字时,代码使用`'0' <= c <= '9'`进行判断,这种方法是否可靠,存在哪些潜在的问题或局限性?
▷