C Programming - String to Integer (atoi)
Another TechMahindra Interview question. The question was to convert a VALID string into its corresponding integer value.Post in your comments!
Solution:
int atoi(char *string)
{
int value=0,sign=1;
if ( !string || !*string ) return 0;
if ( *string == '-' ) {
sign = -1;
string++;
}
while ( *string ) {
if ( (*string >= '0') && (*string <= '9') ) {
value = value * 10 + (*string - '0');
}
else
break;
string++;
}
return sign * value;
}
Labels: C
About this entry
You’re currently reading “
- Published:
- 9:36 pm
- by -
1 Comments (Post a Comment)