6 - String to Integer (atoi)

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.

需要考虑的情况:

1,str是否为空;

2,str头一个数是否为结束符;

3,str是否包含空格,如有,跳过;

4,str是否包含数字正负信息;

5,str中字符是否为0-9之间的字符;

6,在while循环中result是否越界(此处没写,直接写在最后,应该是写在循环里);

7,注意效率;


11/17/2013更新:还需考虑下如果+-号之后为空的情况,处理方法应该以设定一个静态全局然后直接改变其值为佳。代码未更新。



class Solution {
public:
    int atoi(const char *str) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(str == NULL || *str == '\0')
            //throw exception("invalid");
            return 0;
            
        bool ifNeg = false;
        long long result = 0; //?
        while(*str == ' ')
            str++;
        if(*str == '-')//if it is negtive number
        {
            ifNeg = true;
            str++;
        }
        else if(*str == '+')//if it is positive number
        {
            str++;
        }
        
        while(str != '\0')
        {
            
            if( ( ( *str - '0') >= 0) && ( (*str - '0') <= 9 ) )
            {
                int digit = *str - '0';
                result = result *10 + digit;
                str++;
            }
            else //if it is not a digit 
                break;
                
        }
        
        int po = 1;
        if(ifNeg)
            po = -1;
        
        if(result*po > INT_MAX)
            return INT_MAX;
        else if(result*po < INT_MIN)
            return INT_MIN;
        else
            return result*po;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值