# 字符串转换成整数（3种方法）

32 篇文章 0 订阅
33 篇文章 0 订阅
19 篇文章 0 订阅

C++

class Solution {
public:
int myAtoi(string s) {
int i=0;
bool fu = false;
bool chara = false;
vector <int> result;
if(!s[0])
return 0;

while(s[i]==' ')
{
i++;
}
if(s[i]=='-'&&fu==false&&chara==false)
{
fu=true;
chara = true;
i++;
}
if(s[i]=='+'&&chara==false)
{
chara = true;
i++;
}
while(s[i]=='0')
{
i++;
chara=true;
}
while(i<s.size())
{

if(s[i]>='0'&&s[i]<='9')
{
chara = true;
result.push_back(s[i]-'0');
}
else
break;
i++;

}

long sum=0;
int len = result.size();
i=0;
if(len>10&&fu==false)
return INT_MAX;
if(len>10&&fu==true)
return INT_MIN;
while(i<result.size())
{
sum += pow(10,len-1)*(result[i]);
i++;
len--;
}
if(fu)
sum = -sum;
if(sum<INT_MIN)
return INT_MIN;
if(sum>INT_MAX)
return INT_MAX;

return sum;
}
};


class Solution {
public:
int myAtoi(string s) {
int i=0;
bool fu = false;
while(s[i]==' ')
{
i++;
}
if(s[i]=='-')
{
fu=true;
}
if(s[i]=='+'||s[i]=='-')
{
i++;
}
int sum=0;
while(i<s.size()&&isdigit(s[i]))
{

int r = s[i]-'0';

if(sum>INT_MAX/10||(INT_MAX/10==sum&&r>7))//也可用double，不过会慢。
return fu? INT_MIN:INT_MAX;
sum = sum*10 + r;
i++;
}

return fu? -sum:sum;
}
};


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;
}
};



class Solution:
def myAtoi(self, s: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)



C++的正则表达式方法

class Solution {
public:
int sign = 1;
int myAtoi(string s) {
s.erase(0,s.find_first_not_of(" "));
regex e("^[\\+\\-]?\\d+");
smatch m;
bool found = regex_search(s, m, e);
int ans = 0;
string resu = m.str(0);
if(resu[0]=='-')
{
sign = -1;
}
if(resu[0]=='+'||resu[0]=='-')
{
resu.erase(0,1);
}
for(char c : resu)
{
int num = c - '0';
if(ans>INT_MAX/10||(ans==INT_MAX/10&&num>7))
{
return sign==1? INT_MAX:INT_MIN;
}
ans = ans * 10 + num;
}
return sign * ans;
}
};

• 0
点赞
• 0
评论
• 7
收藏
• 打赏
• 扫一扫，分享海报

07-21 1万+
08-30 3133

05-20 197
04-18 226
12-19 97
05-14 1万+
02-13 1323
07-27 9352
02-26 2583
06-26 11万+
06-10 389
06-10 417
06-29 7542
04-03 2826
08-08 3870
05-05 637

_yuan20

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。