π·πΌλͺ¨μ¬λ΄μ κ°λ°μμ²π·πΌ
[JAVA/μ½λ©ν μ€νΈ] νμμ μ°μ°(postfix) λ³Έλ¬Έ
κ°λ°/μκ³ λ¦¬μ¦ λ¬Έμ νμ΄ JAVA
[JAVA/μ½λ©ν μ€νΈ] νμμ μ°μ°(postfix)
μμΌμ΄ 2021. 6. 6. 23:55λ°μν
μ€λͺ
νμμ°μ°μμ΄ μ£Όμ΄μ§λ©΄ μ°μ°ν κ²°κ³Όλ₯Ό μΆλ ₯νλ νλ‘κ·Έλ¨μ μμ±νμΈμ.
λ§μ½ 3*(5+2)-9 μ νμμ°μ°μμΌλ‘ νννλ©΄ 352+*9- λ‘ ννλλ©° κ·Έ κ²°κ³Όλ 12μ λλ€.
μ λ ₯
첫 μ€μ νμμ°μ°μμ΄ μ£Όμ΄μ§λλ€. μ°μ°μμ κΈΈμ΄λ 50μ λμ§ μμ΅λλ€.
μμ 1~9μ μ«μμ +, -, *, / μ°μ°μλ‘λ§ μ΄λ£¨μ΄μ§λ€.
μΆλ ₯
μ°μ°ν κ²°κ³Όλ₯Ό μΆλ ₯ν©λλ€.
μμ μ λ ₯ | μμ μΆλ ₯ |
352+*9- | 12 |
νμ΄
import java.util.*;
public class Main {
public void solution(String str) {
int result = 0;
int a = 0, b = 0, z = 0;
Stack <Integer> stack = new Stack<>();
for(char x : str.toCharArray()) {
// μ°μ°μμ΄λ©΄
if(isOperator(x)) {
b = stack.pop();
a = stack.pop();
z = postFix(a, b, x);
stack.push(z);
// μ°μ°μμ΄ μλλ©΄
}else {
stack.push(Character.getNumericValue(x));
}
}
result = stack.pop();
System.out.println(result);
}
public boolean isOperator(char c) {
if(c == '+' || c=='-' || c=='*' || c == '/' || c == '%') {
return true;
}
return false;
}
public int postFix(int a, int b, char oper) {
if(oper == '+') {
return a+b;
}else if(oper == '-'){
return a-b;
}else if(oper == '*'){
return a*b;
}else if(oper == '/'){
return a/b;
}else{
return a%b;
}
}
public static void main(String args[]) {
Main main = new Main();
Scanner in= new Scanner(System.in);
String str = in.nextLine();
main.solution(str);
}
}
'κ°λ° > μκ³ λ¦¬μ¦ λ¬Έμ νμ΄ JAVA' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[JAVA/μ½λ©ν μ€νΈ] κ΅μ‘κ³Όμ μ€κ³ (0) | 2021.06.14 |
---|---|
[JAVA/μ½λ©ν μ€νΈ] μ λ§λκΈ° (0) | 2021.06.12 |
[JAVA/μ½λ©ν μ€νΈ] κ΄νΈλ¬Έμμ κ±° (0) | 2021.05.26 |
[JAVA/μ½λ©ν μ€νΈ] μ¬λ°λ₯Έ κ΄νΈ (0) | 2021.05.26 |
[JAVA/μ½λ©ν μ€νΈ] λͺ¨λ μλκ·Έλ¨ μ°ΎκΈ° (0) | 2021.05.20 |
Comments