Interview Questions

implement: float evaluate(char* s)......

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

implement: float evaluate(char* s)......

Question:
implement:
float evaluate(char* s)
for example:
input: "1+2.5" output: 3.5
output: "4-5*8+4/2" output: -34


maybe an answer2:


#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iterator>
#include <stack>

using namespace std;
template<typename RT, typename T, typename Trait, typename Alloc>
RT ss_atoi( const std::basic_string<T, Trait, Alloc>& the_string )
{
std::basic_istringstream< T, Trait, Alloc> temp_ss(the_string);
RT num;
temp_ss >> num;
return num;
}

float extract_number(string s, unsigned int& index)
{
string temp = "";

while (s.compare(index, 1, "+", 1) != 0 && s.compare(index, 1, "-", 1) != 0 && s.compare(index, 1, "*", 1) != 0 && s.compare(index, 1, "/", 1) != 0 && index < s.length())
temp.append(1, s[index++]);

float num = ss_atoi<float>(temp);
return num;
}

bool is_operator(string s, unsigned int index)
{
if (s.compare(index, 1, "+", 1) != 0 && s.compare(index, 1, "-", 1) != 0 && s.compare(index, 1, "*", 1) != 0 && s.compare(index, 1, "/", 1) != 0 && index < s.length())
return false;
else
return true;
}

char operator_at(string s, unsigned int& index)
{
if (index < s.length())
{
if (is_operator(s, index))
return s[index++];
}
return NULL;
}

float evaluate(string s)
{
unsigned int index = 0;
stack<float> Stk;
char op;

if (!is_operator(s, 0))
op = '+';
else
op = operator_at(s, index);

while (index < s.length())
{
float v = extract_number(s, index);
float val = 0.0f;
if (op == '-')
v = -1.0f * v;

if (!Stk.empty() && op == '*' || op == '/')
{
float temp = Stk.top();
Stk.pop();
if (op == '*')
temp *= v;
else if (op == '/')
temp /= v;
Stk.push(temp);
}
else
Stk.push(v);

op = operator_at(s, index);
}

float result = 0.0f;
while (!Stk.empty())
{
result += Stk.top();
Stk.pop();
}

return result;

int main()
{
//string expression = "4-5*8+4/2";
float result = 0.0f;
string expression;
cout << "Enter Expression: ";
cin >> expression;

result = evaluate(expression);
cout << "Result of Expression: " << expression << endl;
cout >>result << endl;
system("pause");
}

(Continued on next question...)

Other Interview Questions