返回
如何将字符串转换成整数——详解myAtoi函数
闲谈
2023-03-28 07:46:34
自定义myAtoi函数:从字符串到整数转换的完整指南
前言
在编程中,经常需要将字符串转换为整数。C/C++ 语言中提供了 atoi()
和 stoi()
两个函数来实现此转换,但它们存在局限性。本文将深入探讨 myAtoi()
函数,一个自定义函数,可以处理 atoi()
和 stoi()
无法处理的情况,例如包含非数字字符或空字符串。
myAtoi 函数的基本原理
myAtoi()
函数的原理是,首先跳过字符串中的所有前导空格。然后,根据字符串中的第一个非空格字符,确定是正数还是负数。接下来,它逐个字符地扫描字符串,将每个字符转换为数字并累加,得到最终的整数结果。如果遇到非数字字符,则停止扫描并返回累加结果。
myAtoi 函数的实现
int myAtoi(string str) {
// 跳过前导空格
int i = 0;
while (str[i] == ' ') {
i++;
}
// 确定正负号
int sign = 1;
if (str[i] == '+' || str[i] == '-') {
sign = (str[i] == '-') ? -1 : 1;
i++;
}
// 将字符转换为数字
int result = 0;
while (str[i] >= '0' && str[i] <= '9') {
result = result * 10 + (str[i] - '0');
i++;
}
// 处理溢出情况
if (result * sign > INT_MAX) {
return INT_MAX;
} else if (result * sign < INT_MIN) {
return INT_MIN;
}
// 返回结果
return result * sign;
}
代码示例
string str1 = "123";
int result1 = myAtoi(str1);
cout << result1 << endl; // 输出:123
string str2 = "-456";
int result2 = myAtoi(str2);
cout << result2 << endl; // 输出:-456
string str3 = " +789";
int result3 = myAtoi(str3);
cout << result3 << endl; // 输出:789
string str4 = "10000000000";
int result4 = myAtoi(str4);
cout << result4 << endl; // 输出:2147483647
string str5 = "2147483648";
int result5 = myAtoi(str5);
cout << result5 << endl; // 输出:2147483647
优点
- 处理包含非数字字符或空字符串的情况
- 考虑正负号
- 确保结果不会超出
INT_MAX
或INT_MIN
常见问题解答
myAtoi()
函数的复杂度是多少?
myAtoi()
函数的复杂度为 O(n),其中 n 是字符串的长度。
myAtoi()
函数如何处理小数?
myAtoi()
函数只处理整数,不处理小数。
- 如果字符串中包含非数字字符,
myAtoi()
函数会返回什么?
myAtoi()
函数会停止扫描并返回到遇到的最后一个数字字符累加的结果。
- 如果字符串为空或只包含空格,
myAtoi()
函数会返回什么?
myAtoi()
函数会返回 0。
myAtoi()
函数如何处理科学计数法?
myAtoi()
函数不处理科学计数法。