알고리즘
백준 15815번 천재 수학자 성필 (JAVA)
박카스마시며코딩
2023. 8. 20. 18:39
https://www.acmicpc.net/problem/15815
15815번: 천재 수학자 성필
길이가 100이 넘지 않는 수식이 예제 입력과 같이 공백 없이 입력된다. 수식은 0부터 9까지의 숫자와 연산자 '+', '-', '*', '/' 로만 이루어져 있다. 또한, 수식의 계산 중간 과정의 모든 결과는 항상 2
www.acmicpc.net
저는 스택을 이용해 문제를 해결하였습니다.
처음에는 숫자가 나오면 그 값을 스택에 넣고, 연산자가 나오면 스택에서 두개 빼서 연산해서 다시 스택에 넣어 문제를 해결하였습니다.
package BOJ.etc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
public class BOJ_15815 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String command = br.readLine();
Stack<Integer> number = new Stack<>();
for(int i = 0 ; i < command.length() ; i++){
char ch = command.charAt(i);
if(isNumber(ch)){
number.push(Integer.parseInt(ch+""));
}else{
int num2 = number.pop();
int num1 = number.pop();
int tempNum = operation(ch,num1,num2);
number.push(tempNum);
}
}
int result = number.pop();
System.out.println(result);
}
private static int operation(char ch, int num1,int num2){
if(ch == '*'){
return num1 * num2;
}else if(ch == '/'){
return num1 / num2;
}else if(ch == '+'){
return num1 + num2;
}else if(ch == '-'){
return num1 - num2;
}
return 0;
}
private static boolean isNumber(char ch){
if(ch >= '0' && ch <= '9'){
return true;
}
return false;
}
}