Test instructions
Implement atoi to convert a string to an integer. (easy)
Analysis:
is to pay attention to a variety of special cases, boundary conditions of the judgment, see code comments.
1 classSolution {2 Public:3 intMyatoi (stringstr) {4 intStart =0;5 Long Longresult =0;6 intFlag =0;7 //handling of extra spaces at the beginning8 while(Str[start] = =' ') { 9start++;Ten } One if(Str[start] = ='+') { Astart++; - } - //"+-2" case, else if ... the Else if(Str[start] = ='-') { -start++; -Flag =1; - } + //illegal characters appear at the beginning - if(Str[start] <'0'|| Str[start] >'9') { + return 0; A } at //after the +-number processing, the extra 0 is started. - while(Str[start] = ='0') { -start++; - } - for(inti = start; I < str.size (); ++i) { - //you can have extra numbers later . in if(Str[i] <'0'|| Str[i] >'9') { - return(Flag = =0) ? Result:-result; to } + inttemp = Str[i]-'0'; - //In this way, do not use POW (x, y) theresult = result *Ten+temp; * //Handling of overflow $ if(Result >0x7FFFFFFF ) { Panax Notoginseng return(Flag = =0) ?0x7FFFFFFF:0x80000000; - } the } + if(Flag = =0) { A returnresult; the } + Else { - return-result; $ } $ - } -};
LeetCode8 String to Integer (atoi)