Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.Arrays;
  4.  
  5. public class ArithmeticExpression {
  6.  
  7.  
  8. public static int presmetaj(char c[], int l, int r) {
  9.  
  10. if (r - l == 4){
  11.  
  12. return valueOfNode(c, l+1, r-1);
  13. }
  14.  
  15. int posOfSign = splitExpression (c, l, r);
  16. if (c[posOfSign] == '+'){
  17.  
  18. return presmetaj(c, l+1, posOfSign-1) + presmetaj (c, posOfSign+1, r-1);
  19. }
  20. else {
  21. return presmetaj(c, l+1, posOfSign-1) - presmetaj (c, posOfSign+1, r-1);
  22. }
  23.  
  24. }
  25.  
  26. public static int splitExpression (char[] c, int l, int r){
  27. int numberOfParenthesis = 0;
  28. for (int i = l; i<=r; i++) {
  29. if (c[i] == '('){
  30. numberOfParenthesis++;
  31. }
  32. else if (c[i] == ')'){
  33. numberOfParenthesis--;
  34. }
  35. else if(c[i] == '+' || c[i] == '-'){
  36. if(numberOfParenthesis == 1)
  37. return i;
  38. }
  39. }
  40.  
  41. return 0;
  42.  
  43. }
  44.  
  45. public static int valueOfNode (char[] c, int l, int r){
  46.  
  47. int num1 = Integer.valueOf(String.valueOf(c[l]));
  48. int num2 = Integer.valueOf(String.valueOf(c[r]));
  49.  
  50. if (c[l+1] == '+'){
  51. return num1 + num2;
  52. }
  53. else {
  54. return num1 - num2;
  55. }
  56.  
  57.  
  58. }
  59.  
  60.  
  61.  
  62. public static void main(String[] args) throws Exception {
  63.  
  64. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  65.  
  66. String expression = br.readLine();
  67. char exp[] = expression.toCharArray();
  68.  
  69. int rez = presmetaj(exp, 0, exp.length-1);
  70. System.out.println(rez);
  71.  
  72. br.close();
  73.  
  74. }
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement