[D4] [S/W 문제해결 기본] 9일차 - 사칙연산 - 1232
성능 요약
메모리: 43,556 KB, 시간: 198 ms, 코드길이: 1,704 Bytes
제출 일자
2023-11-16 09:40
출처: SW Expert Academy, https://swexpertacademy.com/main/code/problem/problemList.do
import java.util.Scanner;
class Solution {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
for(int tc = 1; tc <= 10; tc++) {
int n = sc.nextInt();
int[] nums = new int[n+1];
int[][] next = new int[n+1][2];
char[] oper = new char[n+1];
for(int i = 1; i <= n; i++){
int idx = sc.nextInt();
String tmp = sc.next();
if(tmp.equals("+") || tmp.equals("-") || tmp.equals("/") || tmp.equals("*")){
oper[idx] = tmp.charAt(0);
nums[idx] = 0;
next[idx][0] = sc.nextInt();
next[idx][1] = sc.nextInt();
}else{
nums[idx] = Integer.valueOf(tmp);
oper[idx] = ' ';
}
}
int result = recursion(1,nums,next,oper);
System.out.println("#" + tc + " " + result);
}
}
private static int recursion(int pos, int[] nums, int[][] next,char[] oper){
switch (oper[pos]){
case '+':
return recursion(next[pos][0],nums,next,oper) + recursion(next[pos][1] , nums,next, oper);
case '-':
return recursion(next[pos][0],nums,next,oper) - recursion(next[pos][1] , nums,next, oper);
case '/':
return recursion(next[pos][0],nums,next,oper) / recursion(next[pos][1] , nums,next, oper);
case '*':
return recursion(next[pos][0],nums,next,oper) * recursion(next[pos][1] , nums,next, oper);
default:
return nums[pos];
}
}
}
'알고리즘 - SWEA > D4' 카테고리의 다른 글
[SW expert Academy] SWEA 1226번 미로1 자바(Java) (1) | 2023.11.18 |
---|---|
[SW expert Academy] SWEA 3752번 가능한 시험 점수 자바(Java) (0) | 2023.11.16 |
[SW expert Academy] SWEA 1224번 계산기3 자바(Java) (0) | 2023.11.15 |
[SW expert Academy] SWEA 1223번 계산기2 자바(Java) (0) | 2023.11.15 |
[SW expert Academy] SWEA 1222번 계산기1 자바(Java) (0) | 2023.11.15 |