LeetCode 8
String to Integer (atoi)
- Reference:自己写的!对于一个菜鸡来说可以说是hin开心了,写完这篇就去吃点好吃的犒劳一下: )
Problem Description:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.Requirements for atoi:
1. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
2. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
3. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
4. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.Solution:
虽然代码长了不止一点
class Solution {
public:
int myAtoi(string str) {
% 处理空串的情况
if (str.length() == 0) {
return 0;
}
int flag = 1; % 记录字符串可能的正负性
int value = 0; % 作为字符串转换成有效数字的变量
int start = 0; %记录数字的起始位置
int zero_count = 0; % 标记第一个非0开头的数字
for (int i = 0; i < str.length(); i++) {
if (str[i] != ' ') {
start = i;
break;
} % 跳过字符串中所有的空格
}
if (str[start] == '-') {
flag = 0;
start++;
} else if (str[start] == '+') {
start++;
} else if (str[start] > '9' || str[start] < '0') {
return 0;
} % 若出现在+/-后的字符不是数字,则返回0
for (int i = start; i < str.length(); i++) {
if (str[i] == '0' && zero_count == 0) {
continue;
}
if (str[i] != '\0' && str[i] <= '9' && str[i] >= '0') {
zero_count = 1;
% 对正负数的溢出处理不同(-1别忘了,对最后一个字符的判断别忘了)
if (flag == 0) {
if (-1*value < INT_MIN/10) {
return INT_MIN;
} else if (-1*value == INT_MIN/10 && str[i]-'0'>8) {
return INT_MIN;
} else {
value = 10*value+str[i]-'0';
}
} else {
if (value > INT_MAX/10) {
return INT_MAX;
} else if (value == INT_MAX/10 && str[i]-'0' > 7) {
return INT_MAX;
} else {
value = 10*value+str[i]-'0';
}
}
} else {
break;
}
}
if (flag == 0)
return -1*value;
return value;
}
};
本文介绍了一个将字符串转换为整数的方法,实现了LeetCode第8题String to Integer (atoi)的解决方案。文章详细解释了如何处理字符串中的空白字符、正负号以及非数字字符,并给出了具体的实现代码。

1114

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



