| public class StackOper { |
| private IntStack oper1; |
| private IntStack oper2; |
| private IntStack result; |
|
| private String soper1; |
| private String soper2; |
|
| public StackOper(IntStack stack1, IntStack stack2) { |
| oper1 = stack1; |
| oper2 = stack2; |
| result = new IntStack(); |
| } |
|
| public void pushNum(String soper1, String soper2) { |
| this.soper1 = soper1; |
| this.soper2 = soper2; |
| push(soper1, oper1); |
| push(soper2, oper2); |
| } |
|
| private void push(String s, IntStack stack) { |
| char num[] = s.toCharArray(); |
| for (int i = 0; i < num.length; i++) { |
| if (num <= 57 && num >= 48) |
| stack.push(num - 48); |
| else |
| throw new UnsupportedOperationException("Not Digital"); |
| } |
| } |
|
| public void add() { |
| int addition = 0; |
| while (!oper1.empty() && !oper2.empty()) { |
| int sum = oper1.pop() + oper2.pop() + addition; |
| if (sum < 10) { |
| result.push(sum); |
| addition = 0; |
| } else { |
| result.push(sum - 10); |
| addition = 1; |
| } |
| } |
|
| while (addition == 1) { |
| if (!oper1.empty()){ |
| int sum = oper1.pop() + addition; |
| if (sum < 10) { |
| result.push(sum); |
| addition = 0; |
| } else { |
| result.push(sum - 10); |
| addition = 1; |
| } |
| }else if (!oper2.empty()){ |
| int sum = oper2.pop() + addition; |
| if (sum < 10) { |
| result.push(sum); |
| addition = 0; |
| } else { |
| result.push(sum - 10); |
| addition = 1; |
| } |
| }else { |
| result.push(1); |
| addition = 0; |
| } |
| } |
|
| while (!oper1.empty()) |
| result.push(oper1.pop()); |
|
| while (!oper2.empty()) |
| result.push(oper2.pop()); |
| } |
|
| public void printResult() { |
System.out.print("Operator1:" + soper1 + '
'); |
System.out.print("Operator2:" + soper2 + '
'); |
| System.out.print("Result :"); |
| while (result.empty() == false) |
| System.out.print(result.pop()); |
| System.out.println(); |
| } |
|
| public static void main(String[] args) { |
| IntStack int1 = new IntStack(); |
| IntStack int2 = new IntStack(); |
|
| StackOper so = new StackOper(int1, int2); |
| so.pushNum("1313", "19"); |
| so.add(); |
| so.printResult(); |
| } |
| } |