Skip to content

Commit ba026bd

Browse files
committed
atoi
1 parent f639ab8 commit ba026bd

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

src/atoi.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
}

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ pub mod find_median_sorted_arrays;
77
pub mod longest_palindrome;
88
pub mod zigzag_conversion;
99
pub mod reverse_integer;
10+
pub mod atoi;

0 commit comments

Comments
 (0)