結果

問題 No.708 (+ー)の式
ユーザー taotao54321taotao54321
提出日時 2018-09-28 00:57:33
言語 Rust
(1.77.0)
結果
AC  
実行時間 1 ms / 2,000 ms
コード長 1,945 bytes
コンパイル時間 1,086 ms
コンパイル使用メモリ 145,880 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-04-20 09:16:25
合計ジャッジ時間 1,237 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,376 KB
testcase_02 AC 1 ms
5,376 KB
testcase_03 AC 1 ms
5,376 KB
testcase_04 AC 1 ms
5,376 KB
testcase_05 AC 1 ms
5,376 KB
testcase_06 AC 1 ms
5,376 KB
testcase_07 AC 1 ms
5,376 KB
testcase_08 AC 1 ms
5,376 KB
testcase_09 AC 1 ms
5,376 KB
testcase_10 AC 1 ms
5,376 KB
testcase_11 AC 1 ms
5,376 KB
testcase_12 AC 1 ms
5,376 KB
testcase_13 AC 1 ms
5,376 KB
testcase_14 AC 1 ms
5,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::io;
use std::io::prelude::*;
use std::iter;
use std::str;

// expr   ::= term (('+'|'-') term)*
// term   ::= ('+'|'-')? (number | '(' expr ')')
// number ::= \d

fn number(chars: &mut iter::Peekable<str::Chars>) -> i64 {
    let c = chars.next().unwrap();
    c.to_digit(10).unwrap() as i64
}

fn term(chars: &mut iter::Peekable<str::Chars>) -> i64 {
    let mut sign = 1;
    let &c = chars.peek().unwrap();
    match c {
        '+' => { chars.next(); },
        '-' => { chars.next(); sign = -1; },
        _   => {},
    };

    let &c = chars.peek().unwrap();
    let mut res = if c == '(' {
        chars.next();
        let res = expr(chars);
        assert_eq!(')', chars.next().unwrap());
        res
    }
    else {
        number(chars)
    };

    res *= sign;
    res
}

fn expr(chars: &mut iter::Peekable<str::Chars>) -> i64 {
    let mut res = term(chars);

    while let Some(&c) = chars.peek() {
        match c {
            '+' => { chars.next(); res += term(chars); },
            '-' => { chars.next(); res -= term(chars); },
            _   => { break; },
        }
    }

    res
}

fn eval(s: &str) -> i64 {
    let mut chars = s.chars().peekable();
    expr(&mut chars)
}

#[test]
fn test_eval() {
    assert_eq!( 0, eval("0"));
    assert_eq!( 1, eval("1"));
    assert_eq!( 1, eval("+1"));
    assert_eq!(-1, eval("-1"));

    assert_eq!( 3, eval("1+2"));
    assert_eq!( 4, eval("8-4"));
    assert_eq!(-5, eval("-9+4"));
    assert_eq!(-7, eval("-3-4"));

    assert_eq!( 1, eval("(1)"));
    assert_eq!( 5, eval("(2+3)"));
    assert_eq!( 6, eval("(9-3)"));
    assert_eq!( 7, eval("+(4+3)"));
    assert_eq!(-4, eval("-(2+2)"));
    assert_eq!( 1, eval("-(2-3)"));

    assert_eq!(15, eval("-(1+2+3)+(1+2+3+4+5+6)"));
}

fn main() {
    let mut line = String::new();
    io::stdin().read_to_string(&mut line).unwrap();
    let line = line.trim();

    let ans = eval(&line);

    println!("{}", ans);
}
0