String to Integer
Problem:
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.
Ideas:
Just need to consider the corner case more, the idea is simple
My Code:
Public classSolution { Public intmyatoi (String str) {if(str==NULL|| Str.length () ==0 | | Str.trim (). Length () ==0)return0; STR=Str.trim (); BooleanIsplus =true; if(Str.charat (0) = = '-') {Isplus=false; STR= str.substring (1); } Else { if(Str.charat (0) = = ' + ') Str= str.substring (1); } LongRST = 0; for(inti=0; I<str.length (); i++) { Charc =Str.charat (i); if(Isvalidnum (c)) {rst= rst*10 + (c ' 0 '); LongTMP = (isplus? rst:rst*-1); if(Tmp>integer.max_value)returnInteger.max_value; if(Tmp<integer.min_value)returnInteger.min_value; } Else Break; } rst= (isplus? rst:rst*-1); return(int) rst; } Public BooleanIsvalidnum (Charc) {returnc<= ' 9 ' && c>= ' 0 '?true:false; }}
View Code
String to Integer