Implement atoi function (C++ implementation)

  • atoi converts string type to int type.
  • Points to note:

     1 Consider the case of overflow and underflow

     2 Encountered spaces need to be processed

     3 Set a flag to record the sign, if it is "+", flag=1; if it is "-", flag=-1;

     4 Convert the corresponding char type character to an integer, such as s[i]-'0', if the value is less than 0 or greater than 9, it is an abnormal value, and it is returned at this time;

     If the value is between 0-9, update result with result*10+this value.

  • The complete C++ code is as follows:

#include<string>
#include<vector>
#include<iostream>
using namespace std;
int help(string s)
{
int n = s.size();
int i = 0;
int flag = 1;
int ret=0;
if (n == 0)
return 0;
while (s[i] == ' ')
{
i++;
}
if (s[i] == '+')
{
i++;
}
else if (s[i] == '-')
{
i++;
flag = -1;
}
while (i < n)
{
if (s[i]<'0' || s[i]>'9')
{
return ret * flag;
}
int digit = s[i] - '0';
if (flag == 1 && 10.0 * ret + digit >INT_MAX)
{
return  INT_MAX;
}
else if (flag == -1 && -(10.0*ret + digit) < INT_MIN)
{
return INT_MIN;
}
else
ret = 10 * ret + digit;
i++;
}
return ret*flag;
}
int main()
{
string s;
cin >> s;
int result;
result = help(s);
cout << result<<endl;
system("pause");
return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689197&siteId=291194637