Advertisement
Guest User

Untitled

a guest
Jul 28th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. public class PrefixEvaluator {
  2. public static void main(String[] args) {
  3. String input = "(+(+23)(+41))";
  4. // String input = "(1+(+23)(+41))";
  5. // String input = "(++(+23)(+41))";
  6. System.out.println(calculate(input));
  7. }
  8.  
  9. public static int calculate(String str) {
  10. // because prefix doesn't need parenthesses
  11. String clean = str.replaceAll("[()]", ""); // regex: [] = charset
  12. Stack<Integer> stc = new Stack<>();
  13.  
  14. // because prefix, reverse the eval seq
  15. for (int i = clean.length() - 1; i >= 0; i--) {
  16. char c = clean.charAt(i);
  17. if (c == '+') {
  18. if (stc.size() < 2) {
  19. throw new IllegalArgumentException("Invalid expression");
  20. }
  21. stc.push(stc.pop() + stc.pop());
  22. } else {
  23. stc.push(Character.getNumericValue(c));
  24. }
  25. }
  26.  
  27. if (stc.size() != 1) {
  28. throw new IllegalArgumentException("Invalid expression");
  29. }
  30.  
  31. return stc.pop();
  32. }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement