o****d 发帖数: 2835 | 1 http://discuss.leetcode.com/questions/192/string-to-integer-ato
Am I right?
We can separate INT_MAX and INT_MIN to first n-1 digits and last one digit,
which can be used to check overflow before the answer really overflows. Note
that abs(INT_MIN)=INT_MAX+1.
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int pos=0;
//skip whitespace
while(str[pos]==' ')pos++;
//check if negative
int negative=0;
if(str[pos]=='-')
{
negative=1;
pos++;
}
else if(str[pos]=='+')
pos++;
if(str[pos]=='\0') return 0;
//separate INT_MAX to first n-1 digits and the last one digit
//INT_MIN as well
//NOTE that abs(INT_MIN) = INT_MAX + 1
int max1, max2, min1, min2;
max1=INT_MAX/10;
max2=INT_MAX-max1*10;
if(max2+1==10)
{
min1=max1+1;
min2=0;
}
else
{
min1=max1;
min2=max2+1;
}
int ans=0;
while(isdigit(str[pos]))
{
//check if overflow
if(!negative)
{
if(ans>max1 || ans==max1&&(str[pos]-'0')>=max2)
return INT_MAX;
}
else
{
if(ans>min1 || ans==min1&&(str[pos]-'0')>=min2)
return INT_MIN;
}
ans = ans*10+(str[pos]-'0');
pos++;
}
if(negative) ans=-ans;
return ans;
}
int isdigit(char c)
{
if(c>='0' && c<='9')
return 1;
else
return 0;
}
}; |
|