数据结构和算法

string-to-integer-atoi ---> leet

2019-12-03  本文已影响0人  奔跑的蛙牛

Runtime: 0 ms, faster than 100.00% of Rust online submissions for String to Integer (atoi).
Memory Usage: 2.4 MB, less than 100.00% of Rust online submissions for String to Integer (atoi).
Next challenges:
string-to-integer-atoi
思想:状态机


pub fn my_atoi(str: String) -> i32 {
        let (i32_min, i32_max) = (-2_i64.pow(31), 2_i64.pow(31) - 1);
        let mut num_match = false;
        let mut result: i64 = 0;
        let mut minus = false;
        for ch in str.chars().into_iter() {
            if !num_match {
                match ch {
                    ' ' => {}
                    '0'...'9' => {
                        num_match = true;
                        result = result * 10 + ch.to_digit(10).unwrap() as i64;
                    }
                    '-' => {
                        num_match = true;
                        minus = true;
                    }
                    '+' => {
                        num_match = true;
                    }
                    _ => return 0,
                }
            } else {
                match ch {
                    '0'...'9' => {
                        result = result * 10 + ch.to_digit(10).unwrap() as i64;
                        if result > i32_max {
                            break;
                        }
                    }
                    _ => break,
                }
            }
        }
        result = if minus { -result } else { result };
        if result > i32_max {
            return i32_max as i32;
        }
        if result < i32_min {
            println!("cccc:{}", result);
            println!("cccc:{}", i32_min);

            return i32_min as i32;
        }
        return result as i32;
    }
上一篇下一篇

猜你喜欢

热点阅读