[LeetCode]8. String to Integer (atoi)

本文介绍了一个LeetCode上的atoi题目解决方案,该题要求将输入的字符串转换为整数,并处理各种错误输入情况,避免整数溢出等问题。通过C++实现,详细解释了如何判断正负号、数字字符及非数字字符的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接:https://leetcode.com/problems/string-to-integer-atoi/description/

意思是把输入的字符串string转为int。然后会有错误输入,要对这些进行处理。具体要求为Requirements for atoi: 

我的实现:

class Solution {
public:
    int myAtoi(string str) {
        bool initialSign = true;
        bool isPositive = true;
        int result = 0;
        
        for (int i = 0; i < str.length(); i++) {
            if (str[i] == '+' && initialSign) {
                isPositive = true;
                initialSign = false;
            } else if (str[i] == '-' && initialSign) {
                isPositive = false;
                initialSign = false;
            } else if (str[i] >= '0' && str[i] <= '9') {
                if ((abs(result) > (INT_MAX / 10) && isPositive) || (abs(result) == (INT_MAX / 10) && str[i] > '7' && isPositive)) 
                    return INT_MAX;
                else if ((abs(result) > (INT_MAX / 10) && !isPositive) || (abs(result) == (INT_MAX / 10) && str[i] > '8' && !isPositive)) 
                    return INT_MIN;
                result = result * 10 + (str[i] - '0');
                initialSign = false;
            } else if (!initialSign || str[i] != ' ') {
                return isPositive ? result : -1*result;
            }
        }
        
        return isPositive ? result : -1*result;
    }
};

 

总结:仔细考虑错误输入,溢出处理同[LeetCode]7. Reverse Integer

转载于:https://www.cnblogs.com/qianzixuan1996/p/8288567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值