01-25 03:45
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_38 ํ›„์œ„์‹ ์—ฐ์‚ฐ(postfix) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_38 ํ›„์œ„์‹ ์—ฐ์‚ฐ(postfix)

miinsun 2022. 1. 5. 20:04

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

ํ›„์œ„์—ฐ์‚ฐ์‹์ด ์ฃผ์–ด์ง€๋ฉด ์—ฐ์‚ฐํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.
๋งŒ์•ฝ 3*(5+2)-9 ์„ ํ›„์œ„์—ฐ์‚ฐ์‹์œผ๋กœ ํ‘œํ˜„ํ•˜๋ฉด 352+*9- ๋กœ ํ‘œํ˜„๋˜๋ฉฐ ๊ทธ ๊ฒฐ๊ณผ๋Š” 12์ž…๋‹ˆ๋‹ค.

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ์ค„์— ํ›„์œ„์—ฐ์‚ฐ์‹์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์—ฐ์‚ฐ์‹์˜ ๊ธธ์ด๋Š” 50์„ ๋„˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์‹์€ 1~9์˜ ์ˆซ์ž์™€ +, -, *, / ์—ฐ์‚ฐ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„๋‹ค.

352+*9-

์ถœ๋ ฅ - ์—ฐ์‚ฐํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

12

 

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {

	public int solution(String s) {
		int answer = 0;
		Stack<String> stack = new Stack<>();
		//ํ›„์œ„ ๊ณ„์‚ฐ์‹ -> ์ค‘์œ„ ๊ณ„์‚ฐ์‹์œผ๋กœ ๋ฐ”๊พธ๊ธฐ
		for(char c : s.toCharArray()) {
			if(!Character.isDigit(c)) {
				int tmp = 0;
				
				int rt = Integer.parseInt(stack.pop());
				int lt = Integer.parseInt(stack.pop());

				switch(c) {
				case '+':
					tmp = lt + rt;
					break;
				case '-':
					tmp = lt - rt;
					break;
				case '*':
					tmp = lt * rt;
					break;
				case '/':
					tmp = lt / rt;
					break;
				}
				stack.push(Integer.toString(tmp));
			}
			else {
				stack.push(Character.toString(c));
			}
		}
		answer = Integer.parseInt(stack.pop());
        return answer;
	}
	
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		String s = sc.next();
		
		System.out.println(main.solution(s));
		
		sc.close();
		return ;
	}
}

 

 

 

Comments