結果

問題 No.222 引き算と足し算
ユーザー tshig
提出日時 2016-08-18 12:08:57
言語 Ruby
(3.4.1)
結果
AC  
実行時間 89 ms / 1,000 ms
コード長 949 bytes
コンパイル時間 48 ms
コンパイル使用メモリ 7,424 KB
実行使用メモリ 12,288 KB
最終ジャッジ日時 2024-11-15 22:13:33
合計ジャッジ時間 4,006 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 31
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

class Calc0222
  def initialize(args)
    args = args.map { |l| l.chomp.split(/\s+/) }
    @s = args.shift.first
  end

  def run
    stack = []
    @s.scan(/\d+|[+-]/).each do |t|
      case t
      when /\d+/
        t = t.to_i
        loop do
          if stack.empty?
            stack.push(t)
            break
          else
            op = stack.pop
            if stack.last.is_a?(Numeric)
              target = stack.pop
              case op
              when '+'
                stack.push(target - t)
              when '-'
                stack.push(target + t)
              end
              break
            else
              case op
              when '+'
                t = +t
              when '-'
                t = -t
              end
            end
          end
        end
      when '+', '-'
        stack.push(t)
      end
    end
    stack.pop
  end
end

puts Calc0222.new(STDIN.readlines).run if __FILE__ == $0
0