The question
Consider the string of digits 123456789. Consider all arithmetic expression that can be formed by placing + or - interspersed within the string. Examples:
1 + 2 - 345 + 67 - 8 - 9 = 292
123456 - 789 = 122667
Write a Java program that uses a stack to find such a combination that has value 2012.
My Problem
I am stuck with the logic since we have to use two arithmetic operators.
import java.util.*;
public class arithmeticStack {
public static void main (String args[]) {
ArrayList<String> dg = new ArrayList<String>();
Stack<String> digits = new Stack<String>();
int number = 0;
dg.add("1");
dg.add("2");
dg.add("3");
dg.add("4");
dg.add("5");
dg.add("6");
dg.add("7");
dg.add("8");
dg.add("9");
for (int i = 0; i <= dg.size() - 1; i++) {
digits.push(dg.get(i));
}
for (String f : digits){
number += Integer.parseInt(f);
}
while (number == 2012) {
}
}
}
Rough idea, this is what I can think:
Think that there are
8 empty boxesbetween the numbers, which can be either filled by a+,- or nothing. So you can get3^8 = 6561different permutations. Create an array of 8 chars. Now permute this array and find all its possibilities.. sorry I don’t know how to do this right now, maybe someone else can explain it to you, I’m pretty sure it can be done. Use these permutations to insert these values in the original string.You can use a stack to evaluate an expression. Can be done without considering operator precedence in your case roughly like this:
Iterate from left to right, if you encounter an operand, push it to the stack. If you encounter an operator, push it to the stack again. Now when you enter a second operand, pop and retrieve the operator, pop again to retrieve an operand, do the operation with these two operands and the operator, and push the result back to the stack. In the end, you have the result on the stack.
Edit: Or just use Python’s
eval…