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.

思路

題目故意出得很模糊,且鼓勵(lì)不看具體要求直接寫。那就慢慢改進(jìn)吧。
最后總結(jié)下這道題的步驟為:處理空格、處理正負(fù)號(hào)、處理最前面的零、處理數(shù)字、處理溢出、處理結(jié)束。

實(shí)現(xiàn)

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<str.size() && str[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;
    }
};

思考

本來(lái)還想著去寫十六進(jìn)制和八進(jìn)制的字符串,但是發(fā)現(xiàn)根本沒(méi)用=_=
這題有點(diǎn)刁鉆了其實(shí),所以大家都給了差評(píng),哈哈。
不過(guò)考察的內(nèi)容還可以,主要是細(xì)心就行了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容