Lined Notebook

[1222] [Java] 계산기 1

by HeshAlgo

<계산기 1>

문제 설명

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV14mbSaAEwCFAYD&categoryId=AV14mbSaAEwCFAYD&categoryType=CODE

 

내 생각

후위계산법에 대해 찾아보고 코드 구현을 했습니다. 부호를 담는 스택과 숫자를 담는 스택 2가지를 만들어 알고리즘을 구현했습니다. 숫자 스택의 사이즈가 1이 될 경우가 모든 숫자를 더한 경우입니다. 

 

푼 시간

16분 40초

 

작성 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// 계산기1
import java.io.FileInputStream;
import java.util.*;
 
public class E1222 {
 
    public static void main(String args[]) throws Exception {
        String path = "input.txt";
        System.setIn(new FileInputStream(path));
        Scanner sc = new Scanner(System.in);
    
        for(int test_case = 1; test_case <= 10; test_case++) {
            int T = sc.nextInt();
            String str = sc.next();
            Stack<String> numberStack = new Stack<String>();
            Stack<String> signStack = new Stack<String>();
            
            for (int i = 0; i < T; i++) {
                String word = str.charAt(i)+"";
                if (word.equals("+"))
                    signStack.push(word);
                else
                    numberStack.push(word);
            }
            
            while (numberStack.size() != 1) {
                int number1 = Integer.parseInt(numberStack.pop());
                int number2 = Integer.parseInt(numberStack.pop());
                String sign = signStack.pop();
                String sum = Integer.toString(number1 + number2);
                numberStack.push(sum);
            }
            System.out.println("#" + test_case + " " + numberStack.peek());
            
            numberStack.clear();
            signStack.clear();
        
        }
        
    }
    
}
 

 

실행 결과

블로그의 정보

꾸준히 공부하는 개발 노트

HeshAlgo

활동하기