Solution: consider multiple situations
1 # include <cctype> 2 3 class solution {4 public: 5 Int atoi (const char * Str) {6 int signal = 0;/* mark positive and negative, 0 */7 long TMP = 0; 8 9 If (* STR = '\ 0') 10 return 0; 11 while (* Str! = '\ 0') 12 {13 if (* STR = ''& signal! = 0)/* indicates that the digit */14 {15 break; 16} 17 if (* STR = '+') appears before the space ') 18 {19 if (signal = 0)/* No number before the positive sign */20 signal = 1; 21 else22 break; 23} 24 if (* STR = '-') 25 {26 if (signal = 0) 27 signal =-1; 28 else29 break; 30} 31 if (* STR> = '0' & * STR <= '9') 32 {33 If (signal = 0) /* No plus or minus sign before the number appears */34 signal = 1; 35 TMP = TMP * 10 + (* Str)-'0 '); 36} 37 If (TMP * signal)> 2147483647) 38 return int_max; 39 if (TMP * signal) <-2147483648) 40 return int_min; 41 if ((! Isdigit (* Str) & (* Str! = '+') & (* Str! = '-') & (* Str! = '') 42 {43 break; 44} 45 STR ++; 46} 47 If (signal = 0) 48 return 0; 49 else 50 return TMP * signal; 51} 52 };
View code