问题描述:
请你来实现一个 myAtoi(string s) 函数,使其能将字符串转换成一个 32 位有符号整数(类似 C/C++ 中的 atoi 函数)。
问题分析:
首先,需要考虑几个情况:
- 输入字符串为空,返回0。
- 前导空格需要忽略。
- 如果第一个非空字符不是数字、正负号,则返回0。
- 如果数字部分的长度超过了 32 位,则需要截断。
- 需要考虑对于边界值的处理,即最大值和最小值。
有了以上思路,接下来需要逐步实现代码。
#include <stdlib.h>
#include <stdio.h>
#include <limits.h> // 包含INT_MAX和INT_MIN常量
int myAtoi(char *s) {
int len = strlen(s);
int sign = 1; // 符号默认为正
int result = 0;
int i = 0;
// 丢弃前导空格,移动游标i
while (s[i] == ' ') {
i++;
}
// 确定符号
if (s[i] == '-') {
sign = -1;
i++;
} else if (s[i] == '+') {
i++;
}
// 转换数字字符
for (; i < len; i++) {
if (s[i] >= '0' && s[i] <= '9') {
int digit = s[i] - '0';
// 判断是否超过32位
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > 7)) {
return sign > 0 ? INT_MAX : INT_MIN;
}
result = result * 10 + digit;
} else { // 遇到非数字字符,停止转换
break;
}
}
return sign * result;
}
int main() {
char testStr1[] = "42";
char testStr2[] = " -42";
char testStr3[] = "4193 with words";
char testStr4[] = "words and 987";
char testStr5[] = "-91283472332";
printf("%d\n", myAtoi(testStr1)); // 42
printf("%d\n", myAtoi(testStr2)); // -42
printf("%d\n", myAtoi(testStr3)); // 4193
printf("%d\n", myAtoi(testStr4)); // 0
printf("%d\n", myAtoi(testStr5)); // INT_MIN
return 0;
}
在上面的代码中,使用了一个 sign
变量来记录正负号,遇到 ‘-’ 号时,符号为负,遇到 ‘+’ 号时,符号为正。
对于数字转换,使用了一个 result
变量来记录数字,并使用 digit
变量来存储当前字符对应的数字。在处理过程中,需要考虑溢出的情况,当 result
大于 32 位有符号整数的最大值或者小于 32 位有符号整数的最小值时,需要直接返回边界值。
最后,返回 result
与 sign
相乘的结果,即可得到最终结果。