题目描述:
学习:
想法就是按照题意去写,但是在边界条件处有几个问题,总结要注意的问题:
1. "+-12"没有考虑两次出现,应设置次数限制
2. "00000-42a1234"应该是0,而且-+应在第一个字母出现之前
3. " +0 123"空格也应考虑次数
4. 边界条件"2147483646" "-2147483648"应该格外考虑,int所能表示的范围是-2147483648到2147483647,因此对于负数,我们不能先*10+t在考虑正负号,边界条件要注意
class Solution {
public:
int myAtoi(string s) {
int result=0;
int sign=0;int times=0;
for(int i=0;i<s.length();i++)
{
char c=s[i];
if(c==' ')
{
if(times==0)
{}
else
break;
}
else if(c=='-')
{
if(times==0)
sign=1;
else
break;
times++;
}
else if(c=='+')
{
if(times==0)
sign=0;
else
break;
times++;
}
else if(c>='0'&&c<='9')
{
times++;
int t=c-'0';
if(sign==1&&result>214748364)
{
return -2147483648;
}
if(sign==0&&result>214748364)
{
return 2147483647;
}
if(result==214748364)
{
if(sign==1&&t>=8)
{
return -2147483648;
}
else if(sign==0&&t>7)
{
return 2147483647;
}
}
result=result*10+t;
}
else
{
break;
}
}
if(sign==1) result=-result;
return result;
}
};
写完去看了题解,救命死去的回忆在攻击我,很惭愧的说,编译是一门大学中我考的最高的一门,但是也是所有大专业课中最不会的一门,不想看,先复制一下题解,回来再说...
class Automaton {
string state = "start";
unordered_map<string, vector<string>> table = {
{"start", {"start", "signed", "in_number", "end"}},
{"signed", {"end", "end", "in_number", "end"}},
{"in_number", {"end", "end", "in_number", "end"}},
{"end", {"end", "end", "end", "end"}}
};
int get_col(char c) {
if (isspace(c)) return 0;
if (c == '+' or c == '-') return 1;
if (isdigit(c)) return 2;
return 3;
}
public:
int sign = 1;
long long ans = 0;
void get(char c) {
state = table[state][get_col(c)];
if (state == "in_number") {
ans = ans * 10 + c - '0';
ans = sign == 1 ? min(ans, (long long)INT_MAX) : min(ans, -(long long)INT_MIN);
}
else if (state == "signed")
sign = c == '+' ? 1 : -1;
}
};
class Solution {
public:
int myAtoi(string str) {
Automaton automaton;
for (char c : str)
automaton.get(c);
return automaton.sign * automaton.ans;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/string-to-integer-atoi/solution/zi-fu-chuan-zhuan-huan-zheng-shu-atoi-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。