地址:https://leetcode-cn.com/problems/string-to-integer-atoi/
思路:按照題目要求判斷即可
Code:
#include<iostream>
using namespace std;
typedef long long LL;
class Solution {
public:
int myAtoi(string str) {
long long res=0;
int l=0,len=str.length();
while(l<len&&str[l]==' '){
++l;
}
int p=1,Min=1<<31,Max=-(Min+1);
if(l!=len){
if(str[l]=='+') p=1,++l;
else if(str[l]=='-') p=-1,++l;
while(l<len&&str[l]>='0'&&str[l]<='9'){
res=res*10+str[l++]-'0';
if(p*res<Min){
res=Min; break;
}else if(p*res>Max){
res=Max; break;
}
}
res*=p;
}
return res;
}
};
int main()
{
ios::sync_with_stdio(false);
string str;
Solution So;
cin>>str;
cout<<So.myAtoi(str)<<endl;
return 0;
}