String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

C++:
01 const int MAX=214748364;
02 const int MAXINT=2147483647;
03 const int MININT=-2147483648;
04 
05  int atoi(const char *str) {
06      bool mustend=false;
07      int i=0;
08      int sign=1;
09      while(str[i]==‘ ‘)
10          i++;
11      if(str[i]==‘-‘){
12           sign=-1;
13           i++;
14      }else if(str[i]==‘+’){
15           i++;
16      }
17      int tmp=0;
18      while(str[i]!=){
19          if(str[i]==‘ ‘){
20               mustend=true;
21               i++;
22               continue;
23          }
24          if((str[i]>‘9’)||(str[i]<‘0’)||(mustend==true))
25              return tmp*sign;
26          if(tmp>MAX){
27              if(sign==1)
28                  return MAXINT;
29              else
30                  return MININT;
31          }
32          if(tmp==MAX){
33              if((sign==1)&&(str[i]>=‘7’))
34                  return MAXINT;
35              if((sign==-1)&&(str[i]>=‘8’))
36                  return MININT;
37          }
38          tmp=tmp*10+str[i++]‘0’;
39      }
40      return tmp*sign;
41 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s