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.
Note:
1) prefix space
2) plus and minus signs
3) Overflow (long int can be used to prevent overflow)
1 int atoi (const char * str) 2 {3 int flag = 1; 4 int I = 0; 5 long int ret = 0; 6 7 if (NULL = str) 8 return 0; 9 while (str [I]! = '\ 0') & (str [I] = '') 10 I ++; 11 12 if (str [I] =' + ') 13 {14 flag = 1; 15 I ++; 16} 17 else if (str [I] = '-') 18 {19 flag =-1; 20 I ++; 21} 22 23 while (str [I]! = '\ 0') & (str [I]> = '0' & str [I] <= '9 ')) 24 {25 ret = ret * 10 + (str [I]-'0'); 26 if (flag = 1) & (ret * flag> INT_MAX )) 27 return INT_MAX; 28 if (flag =-1) & (ret * flag <INT_MIN) 29 return INT_MIN; 30 I ++; 31} 32 return (int) ret * flag; 33}
Leetcode 8. String to Integer (atoi)