結果

問題 No.708 (+ー)の式
ユーザー Pump0129
提出日時 2018-07-23 03:29:21
言語 Java
(openjdk 23)
結果
AC  
実行時間 157 ms / 2,000 ms
コード長 1,687 bytes
コンパイル時間 2,966 ms
コンパイル使用メモリ 77,132 KB
実行使用メモリ 41,312 KB
最終ジャッジ日時 2024-12-26 05:31:36
合計ジャッジ時間 5,983 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 12
権限があれば一括ダウンロードができます

ソースコード

diff #

package net.ipipip0129.yukicoder.no708;

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 演算用クラスのインスタンスを作成
        Operation operation = new Operation(scan.nextLine());
        System.out.println(operation.getNum());
    }
}

class Operation {
    int num = 0;
    // 0=-,1=+
    int prev_sign = 1;
    Operation(String formula){
        for (int i = 0; i < formula.length(); i++) {
            String str = formula.substring(i, i+1);
            if (str.equalsIgnoreCase("-")) {
                prev_sign = 0;
            } else if (str.equalsIgnoreCase("+")) {
                prev_sign = 1;
            } else if (str.equalsIgnoreCase("(")){ // "("が出てきたら")"までの式を演算クラスで演算し答えを取得
                int end_index = 0;
                for (int j = i; !formula.substring(j, j + 1).equalsIgnoreCase(")"); j++) {
                    end_index = j;
                }
                end_index++;
                Operation operation = new Operation(formula.substring(i + 1, end_index));
                if (prev_sign == 0 ) {
                    num -= operation.num;
                } else {
                    num += operation.num;
                }
                i = end_index;
            } else {
                if (prev_sign == 0) {
                    num -= Integer.parseInt(str);
                } else {
                    num += Integer.parseInt(str);
                }
            }
        }
    }

    public int getNum() {
        return num;
    }
}
0