Microsoft Interview Question
Software Engineer / Developershfrom vijayinterviewquestions.blogspot.com/2007/07/write-your-own-c-program-to-implement.html
// atoi
// precondition: a string ("1234")
// postcondition: a number converted from the input string
// special case: if a string is too long, the converted number could be bigger than 2^32-1 ?
int myatoi (char* string)
{
int sign = 1;
// how many characters in the string
int length = strlen(string);
// handle sign
if (string[0] == '-')
{
sign = -1;
i = 1;
}
for (i; i < length; i++)
{
// handle the decimal place if there is one
if (string[i] == '.')
break;
number = number * 10 + (string[i]- 48);
}
number *= sign;
return number;
}
Above Program takes care of
1. Sign of the number
2. Number augmentation
but do not handle the negative scenario when the integer in string format contains integer which is overflowing the integer type.
- Check the number after augmenting the number
if( number <0){
throw new OverflowException();
}
- Operation number = number * 10 + (string[i]- 48); can be replaced with
number = number<<3 + number>>1 + (string[i]- 48);
use atoi :)
- anonymous November 22, 2009