Problem:8. String to Integer (atoi)
Question
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.
思路
考虑以下几种情况
纯数字类型
"012213" -> 12213
字符串有其他符号情况
"222.22" -> 222
"abcd222" -> 0
"22aba2323"-> 22
带有正负号情况
"+222.22" -> 222
"-22" -> -22
空格情况
" 1212" -> 1212
" +12 123123" -> 12
操作流程
1. 首先除掉字符串前面的空格
2. 如果前面有正负号,优先处理好正负号
3. 截取前面的数字部分做转化(如果字符串最前面的子串是数字,截止到第一个非数字字符)
4. 考虑是否溢出
代码
class Solution {
public:
int myAtoi(string str) {
eraseEmptyCharater(str);
int flag = 1;
int overflow = false;
if (str.size() !=0 && str[0] == '-')
flag = -1;
preprocess(str);
if(str.size() == 0)
return 0;
int result = 0;
int exp = str.size()-1;
for(int i = 0; i < str.size(); i++) {
if (unsigned(result) + unsigned((int(str[i])-48) * pow(10, exp)) > INT_MAX)
overflow = true;
result += (int(str[i])-48) * pow(10, exp);
exp--;
}
if(overflow)
return flag == 1 ? INT_MAX : INT_MIN;
return result*flag;
}
void eraseEmptyCharater(string &str) {
int i = 0;
for (; i < str.size(); i++) {
if (str[i] != ' ')
break;
}
str = str.substr(i, str.size()-i);
}
void preprocess(string &str) {
if(str[0] == '+' || str[0] == '-')
str = str.substr(1, str.size()-1);
string vocabulary = "0123456789";
int lastDigPos = -1;
for(int i = 0; i < str.size(); i++) {
if (vocabulary.find(str[i]) != string::npos)
lastDigPos++;
else break;
}
str = str.substr(0, lastDigPos+1);
}
};