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.
Solution
class Solution {
public:
int myAtoi(string str) {
long result = 0;
int n = str.size(), i0 = 0;
bool isNeg = false;
while ( i0 != n and str[i0] == ' ' ) i0 += 1;
char c = str[i0];
if ( c == '+' ) i0 += 1;
if ( c == '-' ) {
isNeg = true;
i0 += 1;
}
for ( int i = i0; i < n; i++ ) {
if ( str[i] - '0' > 10 or str[i] - '0' < 0 ) return result*(1-2*isNeg);
if ( not isNeg ) {
if ( result < (INT_MAX - (str[i]-'0'))/10.) result = result*10 + str[i] - '0';
else return INT_MAX;
}
else {
if ( result < -((INT_MIN + str[i]-'0')/10.) ) result = result*10 + str[i] - '0';
else return INT_MIN;
}
}
return result*(1-2*isNeg);
}
};
Notes
OVERFLOW bugs me!好好总结处理overflow的细节。。。