Microsoft Interview Question Software Engineer / Developers
0of 0 votesWrite a C program that takes a string ( like "234") and returns the number ( 234)
Write the test cases for your program
how do you check for the large numbers (in C# how to prevent from having run time errors for large numbers)
hfrom 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 on November 22, 2009 Edit | Flag Reply