topic: Implementing String-to-integer conversions
Problem Solving Ideas:
Here are some details that should be noted in this question:
1. String "123" = 123;
2. String "+123" = 123;
3. String "123" =-123;
4. String "-" = 0; "+" = 0;
5. String "123-" = 123;
6. String "21474836478" = 2147483647 (Integer.max_value)
7. The remaining cases are illegal inputs and return 0;
The code is as follows:
1 Public classSolution {2 Public intmyatoi (String str) {3 if(str = =NULL|| Str.length () < 1)4 return0;5 BooleanNegative =false;6 inti = 0;7 Doubleres = 0.0;8String s =Str.trim ();9 intLength =s.length ();Ten if(S.charat (i) < ' 0 '){ One if(S.charat (i) = = '-'){ ANegative =true; - } - Else if(S.charat (i)! = ' + '){ the return0; - } - if(Length = = 1) - return0; +i++; - } + while(I <length) { A intn = (S.charat (i)-' 0 ') ; at if(n >= 0 && N <= 9){ -Res *= 10; -Res + =N; -i + +; - } - Else in Break; - to } + if(negative) { -Res *=-1; the } *res = res >= integer.max_value?Integer.MAX_VALUE:res; $res = res <= integer.min_value?Integer.MIN_VALUE:res;Panax Notoginseng return(int) Res; - } the}
Leetcode8--->string to integer (convert strings to integers)