【题目描述】:
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:
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.
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.
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.
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.
【思路】:
主要是检测字符的有效性与int的溢出情况。
【代码】:
class Solution {
public:
int myAtoi(string str) {
//空字符串直接返回
int len = (int)str.size();
if (len == 0) {
return 0;
}
//去除首尾空格
while (str.at(0) == ' ') {
str = str.erase(0, 1);
}
while (str.at(str.size() - 1) == ' ') {
str = str.erase(str.size() - 1, 1);
}
len = str.size();
//标志符号位和数字开始下标位置
int flag, index;
if (str.at(0) == '-') {
flag = 1;
index = 1;
} else if (str.at(0) == '+') {
flag = 0;
index = 1;
} else {
flag = 0;
index = 0;
}
int result = 0;
//遍历剩余字符
while (index < len) {
int tmpValue = str.at(index) - '0';
//判断是否有效数字
if (tmpValue >= 0 && tmpValue <= 9) {
//判断是否溢出
if ((flag == 0 && result < (INT_MAX - tmpValue) / 10.0) || (flag == 1 && result - 1 / 10.0 < (INT_MAX - tmpValue) / 10.0)) {
result = result * 10 + tmpValue;
} else {
return flag == 1 ? INT_MIN : INT_MAX;
}
} else {
return flag == 1 ? -result : result;
}
++index;
}
return flag == 1 ? -result : result;
}
};