8. String to Integer (atoi)

本文介绍了一个将字符串转换为整数(atoi)的C++实现方法,特别关注了空输入、符号处理、数据溢出及空白字符等问题,并提供了一个具体的代码示例。

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

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Update (2015-02-10):

The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.


唉·,没想到这么简单一个都这么难写。

注意四点情况:

1.输入为空

2.正负号

3.数据溢出

4.空白格


数据溢出不好弄,下面这个方法是利用INT_MAX/10的值和当前result未乘10的值进行比较,判断是否溢出。由于溢出正负极值分别为2147483647   -2147483648,所以为了简练,有两种情况:(1)直接大于INT_MAX/10,说明足够大了,绝对溢出了(2)等于INT_MAX/10,可能会溢出,我们需要再加一个条件判断,是否最后一位大于7。对于正数,2147473648即为最小的溢出值,最后一位大于7。对于负值,如果值为2147483648,虽然没溢出,但是刚好,假设它的值到了这个档次,即时溢出了我们也要返回-2147483648,所以这种情况也应该返回。


class Solution {
public:
    int myAtoi(string str) {
        if(str.size() == 0)
            return 0;
            
        int result = 0;
        int sign = 1;
        int i = 0;
            
        while(str[i] == ' ')
            ++i;
            
        if(str[i] == '-' || str[i] == '+')
            sign = (str[i++] == '-') ? -1 : 1;
        while(str[i] >= '0' && str[i] <= '9'){
            if(result > INT_MAX / 10 || (result == INT_MAX / 10 && str[i]-'0' > 7)){
                return sign == 1 ? INT_MAX : INT_MIN;
            }
            result = result * 10 + str[i++] - '0';
        }   
        return result * sign;
    }   
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值