题目描述
请你来实现一个 atoi 函数,使其能将字符串转换成整数。
参考思路
会比《剑指offer》难一点。使用正则。
参考代码
class Solution:
def myAtoi(self, s: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)
C++版本(推荐)
版本一
class Solution {
public:
int myAtoi(string str) {
int res = 0;
int i = 0;
int flag = 1;
// 1. 检查空格
while (str[i] == ' ') { i++; }
// 2. 检查符号
if (str[i] == '-') { flag = -1; }
if (str[i] == '+' || str[i] == '-') { i++; }
// 3. 计算数字
while (i < str.size() && isdigit(str[i])) {
int r = str[i] - '0';
// ------ 4. 处理溢出,这是关键步骤 ------
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && r > 7)) {
return flag > 0 ? INT_MAX : INT_MIN;
}
// ------------------------------------
res = res * 10 + r;
i++;
}
return flag > 0 ? res : -res;
}
};
版本二
class Solution {
public:
int myAtoi(string str) {
int res = 0;
int i = 0;
int flag = 1;
// 1. 检查空格
while (str[i] == ' ') { i++; }
// 2. 检查符号
if (str[i] == '-') { flag = -1; }
if (str[i] == '+' || str[i] == '-') { i++; }
// 3. 计算数字
while (i < str.size() && isdigit(str[i])) {
int r = str[i] - '0';
// ------ 4. 处理溢出,这是关键步骤 ------
if (flag == 1 && (res > INT_MAX / 10 || (res == INT_MAX / 10 && r >= 7))) {
return INT_MAX;
}
if (flag == -1 && (res > INT_MAX / 10 || (res == INT_MAX / 10 && r >= 8))) {
return INT_MIN;
}
// ------------------------------------
res = res * 10 + r;
i++;
}
return flag > 0 ? res : -res;
}
};
本文详细介绍了一种将字符串转换为整数的方法,通过实现atoi函数。提供了两种C++版本的解决方案,一种使用正则表达式,另一种通过逐字符解析并处理溢出情况。文章深入解析了每一步的逻辑,包括跳过前导空格、处理正负号及数字字符的转换。
519

被折叠的 条评论
为什么被折叠?



