# 方法一：long

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
int strToInt(string str) {
int i = 0, flag = 1;
long res = 0; //默认flag = 1，正数
while (str[i] == ' ') i ++;
if (str[i] == '-') flag = -1;
if (str[i] == '-' || str[i] == '+') i ++;
for (; i < str.size() && isdigit(str[i]); i ++)  {
res = res * 10 + (str[i] - '0');
if (res >= INT_MAX && flag == 1) return  INT_MAX;
if (res > INT_MAX && flag == -1) return  INT_MIN;
}
return flag * res;
}
};

int main(){
string mystring="4193 with words";
Solution S;
cout<<S.strToInt(mystring)<<endl;
system("pause");
return 0;
}


# 方法二：无long，增加了溢出判定

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
int strToInt(string str) {
int i = 0, flag = 1;
int res = 0; //默认flag = 1，正数
while (str[i] == ' ') i ++;
if (str[i] == '-') flag = -1;
if (str[i] == '-' || str[i] == '+') i ++;
for (; i < str.size() && isdigit(str[i]); i ++)  {
if (res > INT_MAX / 10 || (res == INT_MAX / 10 && str[i] - '0' > 7)) //溢出判定
return flag == 1 ? INT_MAX : INT_MIN;
res = res * 10 + (str[i] - '0');
}
return flag * res;
}
};

int main(){
string mystring="4193 with words";
Solution S;
cout<<S.strToInt(mystring)<<endl;
system("pause");
return 0;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

有梦想的coder

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

06-04 38
02-27 95
07-28
01-21 3974
03-06
05-12
09-18