Created
November 27, 2016 09:51
-
-
Save DarinM223/43867dc91d4839b78d7da91a454a3d36 to your computer and use it in GitHub Desktop.
Interview prep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #[derive(PartialEq)] | |
| pub enum State { | |
| BeforePrefixOp, | |
| DigitStart, | |
| } | |
| fn convert_to_int(s: &Vec<u8>) -> i32 { | |
| if s.is_empty() { | |
| return 0; | |
| } | |
| let mut mult = 10_i32.pow((s.len() - 1) as u32); | |
| let mut result = 0; | |
| for b in s.iter() { | |
| let digit = (*b - b'0') as i32; | |
| result += digit * mult; | |
| mult /= 10; | |
| } | |
| result | |
| } | |
| pub fn atoi(s: String) -> i32 { | |
| let mut num_string = Vec::with_capacity(s.len()); | |
| let mut neg = false; | |
| let mut state = State::BeforePrefixOp; | |
| for b in s.bytes() { | |
| match b { | |
| b'+' if state == State::BeforePrefixOp => { | |
| state = State::DigitStart; | |
| } | |
| b'-' if state == State::BeforePrefixOp => { | |
| neg = true; | |
| state = State::DigitStart; | |
| } | |
| b' ' if state == State::BeforePrefixOp => {} | |
| ch => { | |
| if ch <= b'9' && ch >= b'0' { | |
| num_string.push(ch); | |
| state = State::DigitStart; | |
| } else if state == State::BeforePrefixOp { | |
| return 0; | |
| } else { | |
| break; | |
| } | |
| } | |
| } | |
| } | |
| let num = convert_to_int(&num_string); | |
| if neg { -num } else { num } | |
| } | |
| fn main() { | |
| println!("Atoi: {}", atoi("123".to_string())); | |
| println!("Atoi: {}", atoi(" 123".to_string())); | |
| println!("Atoi: {}", atoi(" -123".to_string())); | |
| println!("Atoi: {}", atoi(" -123bb".to_string())); | |
| println!("Atoi: {}", atoi(" +123bb".to_string())); | |
| println!("Atoi: {}", atoi(" ".to_string())); | |
| println!("Atoi: {}", atoi("abcde".to_string())); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment