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.Arrays;
- public class ArithmeticExpression {
- public static int presmetaj(char c[], int l, int r) {
- if (r - l == 4){
- return valueOfNode(c, l+1, r-1);
- }
- int posOfSign = splitExpression (c, l, r);
- if (c[posOfSign] == '+'){
- return presmetaj(c, l+1, posOfSign-1) + presmetaj (c, posOfSign+1, r-1);
- }
- else {
- return presmetaj(c, l+1, posOfSign-1) - presmetaj (c, posOfSign+1, r-1);
- }
- }
- public static int splitExpression (char[] c, int l, int r){
- int numberOfParenthesis = 0;
- for (int i = l; i<=r; i++) {
- if (c[i] == '('){
- numberOfParenthesis++;
- }
- else if (c[i] == ')'){
- numberOfParenthesis--;
- }
- else if(c[i] == '+' || c[i] == '-'){
- if(numberOfParenthesis == 1)
- return i;
- }
- }
- return 0;
- }
- public static int valueOfNode (char[] c, int l, int r){
- int num1 = Integer.valueOf(String.valueOf(c[l]));
- int num2 = Integer.valueOf(String.valueOf(c[r]));
- if (c[l+1] == '+'){
- return num1 + num2;
- }
- else {
- return num1 - num2;
- }
- }
- public static void main(String[] args) throws Exception {
- 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();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement