8. 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.
**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.

思路

题目故意出得很模糊,且鼓励不看具体要求直接写。那就慢慢改进吧。
最后总结下这道题的步骤为:处理空格、处理正负号、处理最前面的零、处理数字、处理溢出、处理结束。

实现

class Solution {
public:
    int myAtoi(string str) {
        long long ans=0;
        int sign=1, i=0;
        while(str[i]==' ') i++;
        if(str[i]=='-'){
            sign *= -1;
            i++;
        }
        else if(str[i]=='+')
            i++;
        if(str[i]=='-' || str[i]=='+') return 0;
        while(str[i]=='0') i++;
        for(; i='0' && str[i]<='9' ; i++){
            ans = ans*10 + (str[i]-'0');
            if(sign>0 && ans > INT_MAX) return INT_MAX;
            if(sign<0 && ans > (-(long long)INT_MIN)) return INT_MIN;
        }
        return ans*sign;
    }
};

思考

本来还想着去写十六进制和八进制的字符串,但是发现根本没用=_=
这题有点刁钻了其实,所以大家都给了差评,哈哈。
不过考察的内容还可以,主要是细心就行了。

你可能感兴趣的:(8. String to Integer (atoi))