題目
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ì)心就行了。