string-to-integer-atoi ---> leetcode

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;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,141评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,425评论 0 23
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,143评论 0 13
  • 我是一个出生在八零末年代的女孩;家里姊妹四个;排行老三。俩个姐姐一个弟弟。爸爸妈妈对于他们那个年代来说是文化人;没...
    钢琴jin阅读 1,683评论 0 1
  • 七月份电影刚上映,就和同事们一起看了这部电影,探讨了教育问题。 今天再次看这部电影,一些语句深入内心。 1.人生...
    微笑向暖f阅读 2,890评论 0 0