8.String to Integer (atoi)

String to Integer (atoi)

  Total Accepted: 40035  Total Submissions: 298259 My Submissions

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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

Show Tags
Have you met this question in a real interview? 
Yes
 
No

/*
注意第一个有效位可以是‘+’、‘-’
注意C++的幂运算符只能用函数pow()
注意发生错误时返回0,用enum标识来区分错误返回的0与正常的
注意要去除前面空白,从第一个非空白处读取,用isspace判断
注意读取有效数字直到遇到第一个非数字字符才结束,这种情况并不是错误情况。
注意溢出时按照题目要求是返回阈值而不是0;并且注意溢出判断:一开始以为用Long long就足够了,但是后来注意到就算longlong也有可能溢出,所以用辅助变量bits_count<10限制有效数字位数不能超过10位
*/
class Solution {
public:
    int atoi(string str) {
        int len=str.size();
        int i=0;
        int bits_count=0;
        //从第一个非空白处读取
        while(i<len && isspace(str[i])){
            ++i;
        }
        long long base=pow(10,len-i-1);
        //用于标识错误情况
        enum states{error,normal};
        states state=normal;
        //判断正负
        enum symbol{negaive,positive};
        symbol flag=positive;
        if(str[i]=='-'){
            flag=negaive;
            ++i;
            base/=10;
        }else if(str[i]=='+'){
            ++i;
            base/=10;
        }
        //空数值
        if(i==len){
            state=error;
            return  0;
        } 
        
        long long res=0;
        while(i<len && bits_count<=10){
            //遇到非数字就不再继续往后读了
            if(str[i]<'0'||str[i]>'9'){ 
                res/=pow(10,len-i);
                break;
            }else{
                res+=(str[i]-'0')*base;
                base/=10;
                ++i;    
                ++bits_count;
            }
        }
        //溢出
        if(flag==negaive){
            res=-res;
            if(res<numeric_limits<int>::min()||bits_count>10){ 
                state=error;
                return numeric_limits<int>::min();
            }
        }else{
            if(res>numeric_limits<int>::max()||bits_count>10){
                state=error;
                return numeric_limits<int>::max();
            }
        }
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值