前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >string-to-integer-atoi ---> leetcode

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

作者头像
用户2436820
修改2023-09-20 18:24:13
4400
修改2023-09-20 18:24:13
举报

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 思想:状态机

代码语言:javascript
复制
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;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档