Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
enum OperatorType
{
Invalid,
Add,
Substract,
Multiply,
Divide
}
input: "5 + 3 * ( 6 - 4 )"
the result is f (exp, 0, 17); // 17 include '\0'
int f (char* exp, int st, int end)
{
int a = INT_MAX;
int b = INT_MAX;
OperatorType op = Invalid;
for (int i=st; i<end+1;)
{
if (IsNum (exp[i]))
{
if (op == Invalid)
{
SetOperand (&a, exp[i]);
}
else
{
SetOperand (&b, exp[i]);
}
i++;
}
else (IsOperator (exp[i]))
{
SetOperator (&op, exp[i]); // translate exp[i] to operator
i++;
}
else (IsLeftBracket (exp[i]))
{
int rightBracketPos = FindRightBracket (exp, i+2, end);
int sub = f (exp, i+2, rightBracketPos-2); // +2, -2 is to skip the space and the current bracket
if (op == Invalid)
{
a = sub;
}
else
{
b = sub;
}
i += rightBracketPos - i + 1; // go to the next space
}
else if (IsSpace (exp[i]) || exp[i] == '\0')
{
if (b != INT_MAX)
{
a = Compute (a, b, op);
b = INT_MAX;
op = Invalid;
}
i++;
}
}
return a;
}
void SetOperand (int *a, int e)
{
if (*a == INT_MAX)
{
*a = e;
}
else
{
*a = (*a) * 10 + e;
}
}
// Expression.cpp : main project file.
#include "stdafx.h"
using namespace System;
typedef int (*operationFun) (int,int);
int add(int a, int b)
{
return a+b;
}
int sub(int a, int b)
{
return a-b;
}
int mul(int a, int b)
{
return a*b;
}
int div(int a, int b)
{
return a/b;
}
operationFun whatToDo(int val)
{
switch(val)
{
case '+':
return add;
case '-':
return sub;
case '*':
return mul;
case '/':
return div;
default:
return 0;
break;
}
}
int main(array<System::String ^> ^args)
{
//char *str = {"5 + 3 * ( ( 6 - 4 ) + ( 2 - 1 ) )"};
char *str = {"5 + 3 * ( 6 - 4 )"};
int stack[15] = {0};
int stackTop = 0;
int op1, op2, op3, val, nextVal, prevVal, prev1Val, prev2Val, prev3Val;
int s1, s2, s3;
int res;
int (*operation) (int,int) = 0;
while(*str != 0)
{
val = *str++;
*str++;
switch(val)
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
stack[stackTop++] = val - '0';
break;
case '+':
case '-':
case '*':
case '/':
operation = whatToDo(val);
nextVal = *str++;
*str++;
if(nextVal >= '0' && nextVal <='9')
{
res = (*operation)(stack[--stackTop], (nextVal-'0'));
stack[stackTop++] = res;
}
if(nextVal == '(')
{
stack[stackTop++] = val;
stack[stackTop++] = '(';
}
break;
case '(':
stack[stackTop++] = val;
break;
case ')':
prevVal = stack[--stackTop]; // will be a number.
prev1Val = stack[--stackTop]; // should be '('
if(stackTop == 0)
{
stack[stackTop++] = prevVal;
}
else
{
prev2Val = stack[--stackTop]; // check wheather is it a '(' or operator.
if(prev2Val == '(')
{
stack[stackTop++] = prev2Val;
stack[stackTop++] = prevVal;
}
else // (8*7)-9+8 ...???
{
prev3Val = stack[--stackTop]; // should be number.
operation = whatToDo(prev2Val);
stack[stackTop++] = operation(prevVal, prev3Val);
}
}
break;
default:
break;
}
}
Console::WriteLine(L"Result :: " + stack[stackTop-1]);
return 0;
}
- Aashish June 24, 2012