Solution #1: Here is the code,
int my_atoi(char* str)
{
int len = strlen(str);
int i;
int isNegative = 0;
int num = 0;
if(str[0] == '-')
{
isNegative = 1;
str++;
}
for(i=0; i < len; i++)
{
int curr = str[i] - '0';
//if it is a digit then put it at the units place
if((curr >=0) && (curr <= 9))
{
num = num*10 + curr;
}
else //if not a digit then break
break;
}
if(isNegative)
num = num*-1;
return num;
}
int main()
{
printf("%d\n", my_atoi("-123"));
return 0;
}
2 comments:
I think you should use 'continue' in else statement?
@anonymous: this behavior is same as the actual atoi() i.e. break when a non-digit is encountered.
Post a Comment