String to Integer (atoi) - LeetCode 8

本文详细解析atoi函数实现中需考虑的多个细节,包括如何判断字符串能否转换成整数,如何处理首部空格、符号,以及如何避免整数越界等问题,并提供了一段C++实现代码。
题目描述:
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.
spoilers alert... click to show requirements for atoi.
Hide Tags Math String

分析:
本题思路很简单,但是要考虑的细节相当多.
要判断一个字符串是否能转换成整数:首先必须是数字字符和首部可能含有符号字符,而且还要判断是否越界。整数范围是[INT_MIN,INT_MAX]
1、首先应该要去掉首部的所有空格
2、判断符号:若第一个空字符是'+'或'-',那么记录符号flag;
3、从第一个非空符号的下一个元素开始,用整型的res来保存结果,循环处理:首先判断是否为数字字符,若不是,则退出循环;否则更新res,每次更新res之前,都要先判断更         新会不会越界,若不不越界,就更新,否则就根据flag返回最大值或最小值。
4、最后返回flag*res;

以下是C++实现代码:

/*//////////////8ms*/
class Solution {
public:
    int myAtoi(string str) {
        if(str.empty())
            return 0;
        int i = 0;
        while(isspace(str[i]))
            i++;
        int flag = str[i] == '-' ?-1:1;
        if(str[i] == '-' || str[i] == '+')
            i++;
        int res = 0;
        for(; i < str.size();i++)
       { 
           if(isdigit(str[i]))
            {
                if(INT_MAX /10 >= res)
                    res *= 10;
                else
                    return (flag==-1)? INT_MIN: INT_MAX;
                if(INT_MAX - (str[i] - '0') >= res)
                    res += (str[i] - '0');
                else
                    return (flag==-1)? INT_MIN: INT_MAX;           
            }
            else
                break;     
       }
        return res * flag;

    }
};


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值