File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ pub fn atoi ( string : & str ) -> Option < i32 > {
2+ let mut f: bool = false ;
3+ let mut res: Vec < char > = Vec :: with_capacity ( string. chars ( ) . count ( ) ) ;
4+ for c in string. chars ( ) . into_iter ( ) {
5+ match c {
6+ '-' | '+' => res. push ( c) ,
7+ '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => {
8+ res. push ( c) ;
9+ f = true ;
10+ }
11+ ' ' => { }
12+ _ => {
13+ if !f {
14+ return None ;
15+ }
16+ }
17+ }
18+ }
19+ if f {
20+ Some ( res. into_iter ( ) . collect :: < String > ( ) . parse :: < i32 > ( ) . unwrap ( ) )
21+ } else {
22+ None
23+ }
24+ }
25+
26+ #[ cfg( test) ]
27+ mod test {
28+ use super :: atoi;
29+
30+ #[ test]
31+ fn test_atoi ( ) {
32+ assert_eq ! ( atoi( "123" ) , Some ( 123 ) ) ;
33+
34+ assert_eq ! ( atoi( " 123" ) , Some ( 123 ) ) ;
35+
36+ assert_eq ! ( atoi( " +123" ) , Some ( 123 ) ) ;
37+
38+ assert_eq ! ( atoi( " -123" ) , Some ( -123 ) ) ;
39+
40+ assert_eq ! ( atoi( " -a123" ) , None ) ;
41+
42+ assert_eq ! ( atoi( " -123a44" ) , Some ( -12344 ) ) ;
43+
44+ assert_eq ! ( atoi( " -xfd" ) , None ) ;
45+
46+ assert_eq ! ( atoi( " " ) , None ) ;
47+ }
48+ }
Original file line number Diff line number Diff line change @@ -7,3 +7,4 @@ pub mod find_median_sorted_arrays;
77pub mod longest_palindrome;
88pub mod zigzag_conversion;
99pub mod reverse_integer;
10+ pub mod atoi;
You can’t perform that action at this time.
0 commit comments