ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

15815๋ฒˆ: ์ฒœ์žฌ ์ˆ˜ํ•™์ž ์„ฑํ•„

๊ธธ์ด๊ฐ€ 100์ด ๋„˜์ง€ ์•Š๋Š” ์ˆ˜์‹์ด ์˜ˆ์ œ ์ž…๋ ฅ๊ณผ ๊ฐ™์ด ๊ณต๋ฐฑ ์—†์ด ์ž…๋ ฅ๋œ๋‹ค. ์ˆ˜์‹์€ 0๋ถ€ํ„ฐ 9๊นŒ์ง€์˜ ์ˆซ์ž์™€ ์—ฐ์‚ฐ์ž '+', '-', '*', '/' ๋กœ๋งŒ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๋˜ํ•œ, ์ˆ˜์‹์˜ ๊ณ„์‚ฐ ์ค‘๊ฐ„ ๊ณผ์ •์˜ ๋ชจ๋“  ๊ฒฐ๊ณผ๋Š” ํ•ญ์ƒ 2

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/15815
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var formula string
	fmt.Fscanln(reader, &formula)
	formulas := strings.Split(formula, "")

	numbers := []int{}
	for len(formulas) > 0 {
		popped := formulas[0]
		formulas = formulas[1:]

		if popped == "+" || popped == "-" || popped == "*" || popped == "/" {
			first := numbers[len(numbers)-2]
			second := numbers[len(numbers)-1]
			numbers = append(numbers[:len(numbers)-2], compute(popped, first, second))
		} else {
			number, _ := strconv.Atoi(popped)
			numbers = append(numbers, number)
		}
	}
	fmt.Fprintln(writer, numbers[0])
}

func compute(operator string, first, second int) int {
	if operator == "+" {
		return first + second
	} else if operator == "-" {
		return first - second
	} else if operator == "*" {
		return first * second
	} else {
		return first / second
	}
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/15815
import sys

def compute(operator, first, second):
    if operator == "+":
        return first + second
    elif operator == "-":
        return first - second
    elif operator == "*":
        return first * second
    else:
        return first // second

if __name__ == "__main__":
    formulas = list(sys.stdin.readline().rstrip())
    numbers = []
    while len(formulas) > 0:
        popped = formulas.pop(0)
        if popped == "+" or popped == "-" or popped == "*" or popped == "/":
            second = numbers.pop(-1)
            first = numbers.pop(-1)
            numbers.append(compute(popped, first, second))
        else:
            numbers.append(int(popped))
    print(numbers[0])

 

728x90
๋Œ“๊ธ€