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;
    }
};
相关推荐
freexyn10 分钟前
Matlab入门自学七十四:坐标系转换,直角坐标、极坐标和球坐标的转换
开发语言·算法·matlab
咱就是说不配啊17 分钟前
3.20打卡day34
数据结构·c++·算法
小张会进步22 分钟前
数组:二维数组
java·javascript·算法
佑白雪乐40 分钟前
LCR 175. 计算二叉树的深度
算法·深度优先
阿Y加油吧1 小时前
力扣打卡day07——最大子数组和、合并区间
算法
想吃火锅10051 小时前
【leetcode】105. 从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
圣保罗的大教堂1 小时前
leetcode 3567. 子矩阵的最小绝对差 中等
leetcode
2401_831824961 小时前
嵌入式C++驱动开发
开发语言·c++·算法
靠沿1 小时前
【优选算法】专题十八——BFS解决拓扑排序问题
算法·宽度优先
cui_ruicheng1 小时前
C++数据结构进阶:哈希表实现
数据结构·c++·算法·哈希算法·散列表