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;
    }
};
相关推荐
bkspiderx1 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐2 小时前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸3 小时前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
tju新生代魔迷3 小时前
数据结构:双向链表
数据结构·链表
一只懒洋洋3 小时前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类
方案开发PCBA抄板芯片解密4 小时前
什么是算法:高效解决问题的逻辑框架
算法
songx_995 小时前
leetcode9(跳跃游戏)
数据结构·算法·游戏
学c语言的枫子5 小时前
数据结构——双向链表
c语言·数据结构·链表
小白狮ww5 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥5 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud