Topic:
Implement atoi to convert a string to an integer.
Hint:carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
Notes:it is intended-problem to be specified vaguely (ie, no given input specs). You is responsible to gather all the input requirements up front.
Although is a simple problem, but to consider a lot of details, such as input empty string words how to output, input has +,-number words, how to do, if encountered invalid input? How does the digital overflow out of the output? If you have an interview, it's best to get it straight.
classSolution { Public: intMyatoi (stringstr) { if(str = ="")return 0; intFlag =1; intres =0; string:: Const_iterator iter =Str.begin (); while(*iter = =' '&& iter! = Str.end ()) iter++; if(*iter = ='+'|| *iter = ='-'){ if(*iter = ='-') flag =-1; *iter++; } while(Iter!=str.end () && isvalidnum (*iter)) { intTMP = *iter-'0'; if(Res > (int_max-tmp)/Ten&& flag = =1)returnInt_max; if(Res > (int_max-tmp)/Ten&& flag = =-1)returnint_min; Res= Res *Ten+tmp; ITER++; } returnflag*Res; } BOOLIsvalidnum (Charc) {returnC >='0'&& C <='9'; }};
"Leetcode" 8. String to Integer (atoi)