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 class Solution {
02 public:
03     int atoi(const char *str) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         int result=0;
07         int sign=1;
08         int p=0;
09         int max=INT_MAX;
10         int min=INT_MIN;
11         while(str[p]==‘ ‘) p++;
12         if(str[p]==‘-‘)
13         {
14             sign=-1;
15             p++;
16         }
17         if(str[p]==‘+’)
18         {
19             p++;
20         }
21         while((str[p]>=‘0’)&&(str[p]<=‘9’))
22         {
23             if(result>max/10)
24             {
25                 return sign>0?INT_MAX:INT_MIN;
26             }
27             if(result*10>maxstr[p]+‘0’)
28             {
29                 return sign>0?INT_MAX:INT_MIN;
30             }
31             result=result*10+str[p++]‘0’;
32         }
33         return sign>0?result:result;
34     }
35 };
Advertisements
This entry was posted in Number trick, 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