Leetcode requires that the output of -91283472332
be converted to int, and the output result is -2147483648
. I use long to store the result, and then return int. Why is the result returned -1089159116
here's my code
int myAtoi(char * s){
char *str = s;
long n = 0;
char *flag ;
while(*str){
if( * str =='-' || * str == '+')
{
flag = str++;
continue;
}
if(*str<='9' && *str>='0')
{
n*=10;
n+=(*str++)-48;
continue;
}
if(*str>='A'&&*str<='z')
break;
++str;
}
if(*flag == '-')
{
n-=(2*n);
}
return n;
}
So here's the description
- Input: s = "-91283472332"
- Output: -2147483648
- Explanation:
Step 1:
"-91283472332" (no characters read because there is no leading whitespace) ^
Step 2:
"-91283472332" ('-' is read, so the result should be negative) ^
Step 3:
"-91283472332" ("91283472332" is read in) ^
The parsed integer is -91283472332. Since -91283472332 is less than the lower bound of the range [-231, 231 - 1], the final result is clamped to -231 = -2147483648.