Leetcode8.字符串转换整数 -codetop


代码(首刷看解析 2024年9月5日)

cpp 复制代码
class Solution {
public:
    int myAtoi(string str) {
        unsigned long len = str.length();

        // 去除前导空格
        int index = 0;
        while (index < len) {
            if (str[index] != ' ') {
                break;
            }
            index++;
        }

        if (index == len) {
            return 0;
        }

        int sign = 1;
        // 处理第 1 个非空字符为正负符号,这两个判断需要写在一起
        if (str[index] == '+') {
            index++;
        } else if (str[index] == '-') {
            sign = -1;
            index++;
        }

        // 根据题目限制,只能使用 int 类型
        int res = 0;
        while (index < len) {
            char curChar = str[index];
            if (curChar < '0' || curChar > '9') {
                break;
            }

            if (res > INT_MAX / 10 || (res == INT_MAX / 10 && (curChar - '0') > INT_MAX % 10)) {
                return INT_MAX;
            }
            if (res < INT_MIN / 10 || (res == INT_MIN / 10 && (curChar - '0') > -(INT_MIN % 10))) {
                return INT_MIN;
            }

            res = res * 10 + sign * (curChar - '0');
            index++;
        }
        return res;
    }
};
相关推荐
leoufung3 分钟前
LeetCode 322. Coin Change:从错误思路到正确一维 DP
算法·leetcode·职场和发展
旧梦吟6 分钟前
脚本网页 双子星棋
算法·flask·游戏引擎·css3·html5
ullio12 分钟前
arc205d - Non-Ancestor Matching
算法
wa的一声哭了19 分钟前
内积空间 正交与正交系
java·c++·线性代数·算法·矩阵·eclipse·云计算
SWAGGY..23 分钟前
数据结构学习篇(8)---二叉树
数据结构·学习·算法
星轨初途25 分钟前
牛客小白月赛126
开发语言·c++·经验分享·笔记·算法
leoufung30 分钟前
动态规划DP 自我提问模板
算法·动态规划
爱编程的小吴37 分钟前
【力扣练习题】热题100道【哈希】560. 和为 K 的子数组
算法·leetcode·哈希算法
じ☆冷颜〃37 分钟前
基于多数据结构融合的密码学性能增强框架
数据结构·经验分享·笔记·python·密码学
Swift社区42 分钟前
LeetCode 463 - 岛屿的周长
算法·leetcode·职场和发展