Sollicitatievraag bij Dropbox
Write a function called eval, which takes a string and returns a boolean. This string is allowed 6 different characters: 0, 1, &, |, (, and ). Eval should evaluate the string as a boolean expression, where 0 is false, 1 is true, & is an and, and | is an or. An example string might look like "(0 | (1 | 0)) & (1 & ((1 | 0) & 0))"
Antwoorden op sollicitatievragen
1) Push the characters onto the stack.
2) Whenever you find a ')', pop all the characters until u see a '(' and evaluate the expression, with the result pushed again on the prev stack.
3) Continue.
This is my answer. Hope it helps
#include "bits/stdc++.h"
using namespace std;
stack > num_stack;
stack > op_stack;
void calculate(){
int num1 = num_stack.top();
num_stack.pop();
int num2 = num_stack.top();
num_stack.pop();
char sign = op_stack.top();
op_stack.pop();
if (sign == '&')
num_stack.push(num1&num2);
else
num_stack.push(num1|num2);
return;
}
int main()
{
cin.sync_with_stdio(false);
string in;
cin >> in;
for (int i = 0; i < in.size(); ++i)
{
if (in[i] == ')'){
calculate();
}
else {
if (in[i] == '1' || in[i] == '0')
num_stack.push(in[i] - '0');
else if (in[i] == '|' || in[i] == '&')
op_stack.push(in[i]);
}
}
while(!num_stack.empty() && !op_stack.empty())
calculate();
cout << num_stack.top() << endl;
return 0;
}