728x90
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비 - 인프런 | 강의
자바(Java)로 코딩테스트를 준비하시는 분을 위한 강좌입니다. 코딩테스트에서 가장 많이 출제되는 Top 10 Topic을 다루고 있습니다. 주제와 연동하여 기초문제부터 중급문제까지 단계적으로 구성
www.inflearn.com
5-4번
import java.util.Scanner;
import java.util.Stack;
public class Main {
public int solution(String ar){
Stack<Integer> stack = new Stack<>();
String[] arr = ar.split("");
int a = 0;
int b = 0;
for(String x : arr){
if(x.matches("-?\\d+")){
stack.push(Integer.parseInt(x));
}else{
switch(x){
case "+":
a = stack.pop();
b = stack.pop();
stack.push(b+a);
break;
case "-":
a = stack.pop();
b = stack.pop();
stack.push(b-a);
break;
case "*":
a = stack.pop();
b = stack.pop();
stack.push(b*a);
break;
case "/":
a = stack.pop();
b = stack.pop();
stack.push(b/a);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args){
Main t = new Main();
Scanner in = new Scanner(System.in);
String arr = in.nextLine();
in.close();
System.out.print(t.solution(arr));
}
}
>>>>>코드 정리>>>>>
import java.util.Scanner;
import java.util.Stack;
public class Main {
public int solution(String arr){
Stack<Integer> stack = new Stack<>();
int a = 0;
int b = 0;
for(char x : arr.toCharArray()){
if(Character.isDigit(x)){
stack.push(x-48);
}else{
switch(x){
case '+':
a = stack.pop();
b = stack.pop();
stack.push(b+a);
break;
case '-':
a = stack.pop();
b = stack.pop();
stack.push(b-a);
break;
case '*':
a = stack.pop();
b = stack.pop();
stack.push(b*a);
break;
case '/':
a = stack.pop();
b = stack.pop();
stack.push(b/a);
break;
}
}
}
return stack.pop();
}
public static void main(String[] args){
Main t = new Main();
Scanner in = new Scanner(System.in);
String arr = in.nextLine();
in.close();
System.out.print(t.solution(arr));
}
}
'오늘의 취준 > 오늘의 코테' 카테고리의 다른 글
[JAVA] 알고리즘 문제풀이 입문 5-6 (0) | 2023.07.13 |
---|---|
[JAVA] 알고리즘 문제풀이 입문 5-5 (0) | 2023.07.12 |
[JAVA] 알고리즘 문제풀이 입문 5-2, 5-3 (0) | 2023.07.07 |
[JAVA] 알고리즘 문제풀이 입문 4-5 (0) | 2023.07.06 |
[JAVA] 알고리즘 문제풀이 입문 4-4번 (0) | 2023.06.29 |