Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.NoSuchElementException;
- public class ArithmeticExpression {
- // funkcija za presmetuvanje na izrazot pocnuvajki
- // od indeks l, zavrsuvajki vo indeks r
- static int presmetaj(char c[], int l, int r) {
- StringBuilder sb= new StringBuilder();
- for(int i =l; i<=r; i++)
- {
- sb.append(c[i]);
- }
- String s=sb.toString();
- ArrayStack<String> numbers= new ArrayStack<String>(r);
- ArrayStack<String> operators= new ArrayStack<String>(r);
- for(int i=0; i<s.length(); i++){
- char ch=s.charAt(i);
- if(Character.isDigit(ch))
- {
- numbers.push(Character.toString(ch));
- }
- else if(ch=='+' || ch=='-' || ch=='/' || ch=='*')
- {
- operators.push(Character.toString(ch));
- }
- else if(c[i]==')'){
- int num2=Integer.parseInt(numbers.pop());
- int num1=Integer.parseInt(numbers.pop());
- char oper=operators.pop().charAt(0);
- if(oper=='+')
- {
- numbers.push(Integer.toString(num1+num2));
- }
- else if(oper=='-')
- {
- numbers.push(Integer.toString(num1-num2));
- }
- }
- }
- return Integer.parseInt(numbers.pop());
- }
- public static void main(String[] args) throws Exception {
- int i,j,k;
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String expression = br.readLine();
- char exp[] = expression.toCharArray();
- int rez = presmetaj(exp, 0, exp.length-1);
- System.out.println(rez);
- br.close();
- }
- }
- class ArrayStack<E> implements Stack<E> {
- private E[] elems;
- private int depth;
- @SuppressWarnings("unchecked")
- public ArrayStack (int maxDepth) {
- // Creating new empty stack
- elems = (E[]) new Object[maxDepth];
- depth = 0;
- }
- public boolean isEmpty () {
- // Returns true only if the stack is empty.
- return (depth == 0);
- }
- public E peek () {
- // Returns the element on the top od the stack.
- if (depth == 0)
- throw new NoSuchElementException();
- return elems[depth-1];
- }
- public void clear () {
- // Clears the stack.
- for (int i = 0; i < depth; i++) elems[i] = null;
- depth = 0;
- }
- public void push (E x) {
- // Adds x on the top of the stack.
- elems[depth++] = x;
- }
- public E pop () {
- // Removes and returns the element on the top.
- if (depth == 0)
- throw new NoSuchElementException();
- E topmost = elems[--depth];
- elems[depth] = null;
- return topmost;
- }
- }
- interface Stack<E> {
- // The elements of the Stack are any kind of objects
- // Access methods:
- public boolean isEmpty ();
- // Returns true only if the stack is empty.
- public E peek ();
- // Returns the element on the top od the stack.
- // Transformation methods:
- public void clear ();
- // Clears the stack.
- public void push (E x);
- // Adds x on the top of the stack.
- public E pop ();
- // Removes and returns the element on the top.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement