Microsoft Interview Question
Software Engineer in TestsCountry: United States
Interview Type: In-Person
Yes its simple mathematics. And this simple observation was made by Horner. Its good to know what the actual mathematical rule is called.
I'd like to contribute to this discussion by saying that I really hate it when absolutely trivial results are called rules or theorems and have a name attached to them. I see you, DeMorgan, I see you.
1. Valid inputs are "123", "+123","-123"
2. Invalids inputs are "1+23","12-3","*123"
3. Integer overflow case for large string ("21323333333333333332"), my code returns so far calculated integer value
long StringToNum( char *str, int len )
{
if( str == NULL || len < 1 )
{
printf(" Invalid input ");
return -1 ; // error code -1
}
else
{
long num = 0, num1 ;
while( len )
{
if( '0' <= str[len-1] && str[len-1] >= '9' )
{
num1 = num;
num = num * 10 + (int) (str[len] - '0' );
if(num1 > num )
{
printf("\n integer overflow " );
return num1;
}
}
else if( (len == 1 ) )
{
if(str[len-1] == '-' )
{
num *= -1 ;
}
else if (str[len-1] != '+' )
{
printf(" Invalid input ");
return -1; // invalid input
}
}
else
{
printf(" Invalid input ");
return -1;
}
len -- ;
}
return num;
}
}
Please letme know if you notice any mistake in my code
I think error checking for decimal point , special characters , integer overflow , +/- etc is important .
Perhaps your exact suggestions weren't quite right, but on a relatively easy question like this, the interviewer would in fact be looking at how careful you're being.
I will post the code momentarily, but this is essentially checking if you know Horner's rule. Let me explain the rule below and converting it to code should be extremely simple:
Say, you are reading a string of numbers left to right: 2 3 6. The problem with this model of reading is that we cannot tell if 2 is a "hundred" or a "ten" or a "thousand". We cannot glean this information, without reading the whole string and using some data structure (or variable(s)) to store the position, which is needlessly inefficient.
So this Horner guy really nailed the problem (no pun intended). What you do is that you read the first number "2" and store it in a variable, say "num".
Then you read "3" and you simply multiply "num" by 10 and add 3 = (2*10)+3=23
Then you read "6" and you multiply "num" by 10 again and add 6 = (23*10)+6=236
Viola! Suddenly you have the correct number.
Now how to do this with string. Well we can make a simple assumption and that is that the string is ASCII so every time we read a character, we simply subtract '0' or 47 from it and we transform it to a valid number
{{
Code in C#/Psuedo (the code is essentially so simple, that I am just going to use a combo of C# and English)
- Anonymous January 18, 2012