atoi — 隐式数据类型转换

本文深入探讨了C++中将字符串转换为整数的myAtoi函数实现,包括空字符串处理、前导空白字符跳过、正负号识别以及防止整数溢出的策略。

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


class Solution {
public:
    int myAtoi(string str) {
        if(str.empty())
        {
            return 0;
        }    

    string::const_iterator itor = str.begin();
    for(; itor != str.end(); ++itor)
    {
        if(isspace(*itor))
        {
            continue;
        }
        break;
    }

    long long nRet = 0; // 如果这里定义的数据类型为int,后面的实现方式会产生溢出错误
    bool isPas = true;

    if(*itor == '+')
    {
        ++itor;
    }
    else if(*itor == '-')
    {
        ++itor;
        isPas = false;
    }    

    for(; itor != str.end(); ++itor)
    {
        if(*itor >= '0' && *itor <= '9')
        {
            // long long llTemp = nRet * 10;
            // 如果nRet是int类型,则nRet * 10就已经溢出了,  
            // 将其赋值给long long型的数据也是错误的结果。  
            // 所以nRet必须为long long型数据。
            // llTemp = llTemp + *itor - '0';
            nRet *= 10;
            nRet += *itor - '0';

            bool isOver = isPas ? nRet > INT_MAX : -nRet < INT_MIN;
            if(isOver)
            {
                return isPas ? INT_MAX : INT_MIN;
            }
        }
        else
        {
            return isPas ? nRet : -nRet;
        }
    }    

    return isPas ? nRet : -nRet;
}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值