Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.NoSuchElementException;
- public class Zagradi<E>{
- public static class ArrayStack<E> {
- // Stekot e pretstaven na sledniot nacin:
- //depth e dlabochinata na stekot, a
- // elems[0...depth-1] se negovite elementi.
- private E[] elems;
- private int depth;
- @SuppressWarnings("unchecked")
- public ArrayStack (int maxDepth) {
- // Konstrukcija na nov, prazen stek.
- elems = (E[]) new Object[maxDepth];
- depth = 0;
- }
- public boolean isEmpty () {
- // Vrakja true ako i samo ako stekot e prazen.
- return (depth == 0);
- }
- public E peek () {
- // Go vrakja elementot na vrvot od stekot.
- if (depth == 0)
- throw new NoSuchElementException();
- return elems[depth-1];
- }
- public void clear () {
- // Go prazni stekot.
- for (int i = 0; i < depth; i++) elems[i] = null;
- depth = 0;
- }
- public void push (E x) {
- // Go dodava x na vrvot na stekot.
- elems[depth++] = x;
- }
- public E pop () {
- // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
- if (depth == 0)
- throw new NoSuchElementException();
- E topmost = elems[--depth];
- elems[depth] = null;
- return topmost;
- }
- }
- public static boolean isDigit(char x) {
- int a = (int) x;
- return( a == 1 || a == 2 || a == 3 || a == 4 || a == 5 || a == 6 || a == 7 || a == 8 || a == 9);
- }
- public static int evaluacija (char exp[]) {
- ArrayStack<Integer> stekce = new ArrayStack<Integer>(100);
- for(int i=0;i<exp.length;i++) {
- if (isDigit(exp[i])) {
- int a = (int) exp[i];
- stekce.push(a);
- }
- else if (exp[i] == '+' || exp[i] == '*') {
- int x = stekce.pop();
- int y = stekce.pop();
- if (exp[i] == '+') {
- int z = x + y;
- stekce.push(z);
- }
- if (exp[i] == '*') {
- int z = x * y;
- stekce.push(z);
- }
- }
- }
- return stekce.pop();
- }
- public static void main (String[] args) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String expression = br.readLine();
- char exp[] = expression.toCharArray();
- int x = evaluacija(exp);
- System.out.print(x);
- br.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement