본문 바로가기

Java/Java 알고리즘 인프런

[Ch.04 - StackQueue] 04. 후위식 연산(postfix) (+ char to int)

반응형

 

4. 후위식 연산(postfix)
 

설명

후위연산식이 주어지면 연산한 결과를 출력하는 프로그램을 작성하세요.

만약 3*(5+2)-9 을 후위연산식으로 표현하면 352+*9- 로 표현되며 그 결과는 12입니다.

입력

첫 줄에 후위연산식이 주어집니다. 연산식의 길이는 50을 넘지 않습니다.

식은 1~9의 숫자와 +, -, *, / 연산자로만 이루어진다.

출력

연산한 결과를 출력합니다.

 

예시 입력 1 

352+*9-

예시 출력 1

12

import java.util.Scanner;
import java.util.Stack;

public class Main {
	public int solution(String str) {
		int answer=0;
		Stack<Integer> stack = new Stack<>();
		for (char x : str.toCharArray()) {
			if (x == '+') {
				int tmp = stack.pop();
				stack.push(stack.pop() + tmp);
			} else if (x == '-') {
				int tmp = stack.pop();
				stack.push(stack.pop() - tmp);
			} else if (x == '*') {
				int tmp = stack.pop();
				stack.push(stack.pop() * tmp);
			} else if (x == '/') {
				int tmp = stack.pop();
				stack.push(stack.pop() / tmp);
			} else
				stack.push(Character.getNumericValue(x));
		}

		return answer=stack.pop();
	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		String str = kb.next();
		System.out.println(T.solution(str));
	}

}
import java.util.*;

public class Main {
	public int solution(String str) {
		Stack<Integer> stack = new Stack<>();
		int tmp1 = 0;
		int tmp2 = 0;
		for (Character c : str.toCharArray()) {
			if (Character.isDigit(c)) {
				stack.push(Character.getNumericValue(c));
			}
			if (c == '+') {
				tmp2 = stack.pop();
				tmp1 = stack.pop();
				stack.push((tmp1 + tmp2));
			} else if (c == '-') {
				tmp2 = stack.pop();
				tmp1 = stack.pop();
				stack.push((tmp1 -tmp2));
			} else if (c == '/') {
				tmp2 = stack.pop();
				tmp1 = stack.pop();
				stack.push((tmp1 / tmp2));
			} else if (c == '*') {
				tmp2 = stack.pop();
				tmp1 = stack.pop();
				stack.push( (tmp1 * tmp2));
			}
		}

		return stack.pop();

	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		String str = kb.next();
		System.out.print(T.solution(str));
	}
}

 

 

+) 세련된 풀이

-> Character형 숫자를 int형 숫자로 변경하는 방법

1. Character.getNumericValue(x);

2. x-48 [48은 0의 아스키코드값으로 뺄 경우 숫자형의 아스키코드로 바뀐다.]

 

풀이 과정

1. 숫자형이면 ->  Character형을 숫자형으로 변경후 stack에 삽입

2. 숫자형이 아니면 -> 스택에서 꺼내 먼저 꺼낸 수를 rt로 나중에 꺼낸 수를 lt로 

-> 사칙연산대로 처리

import java.util.Scanner;
import java.util.Stack;

public class Main {
	public int solution(String str) {
		int answer=0;
		Stack<Integer> stack = new Stack<>();
		for(char x: str.toCharArray()) {
			if(Character.isDigit(x)) {
				stack.push(x-48);
			}
			else {
				int rt=stack.pop();
				int lt=stack.pop();
				if(x=='+') stack.push(lt+rt);
				else if(x=='-') stack.push(lt-rt);
				else if(x=='*') stack.push(lt*rt);
				else if(x=='/') stack.push(lt/rt);
			}
		}
		
		return answer=stack.pop();		
	}
	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		String str=kb.next();
		System.out.println(T.solution(str));
	}

}
import java.util.Scanner;
import java.util.Stack;

public class Main {
	public int solution(String str) {
		int answer=0;
		Stack<Integer> stack = new Stack<>();
		for(char x: str.toCharArray()) {
			if(Character.isDigit(x)) {
				stack.push(x-48);
			}
			else {
				int rt=stack.pop();
				int lt=stack.pop();
				if(x=='+') stack.push(lt+rt);
				else if(x=='-') stack.push(lt-rt);
				else if(x=='*') stack.push(lt*rt);
				else if(x=='/') stack.push(lt/rt);
			}
		}
		
		return answer=stack.pop();		
	}
	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		String str=kb.next();
		System.out.println(T.solution(str));
	}

}

1. char to int

(1) Integer.parseInt(Character.toString(c))

(2) Character.getNumericValue(c);

 

import java.util.*;
  
public class Main {
  public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    String str= in.next();
    System.out.println(Solution(str));
  }
  private static int Solution(String str){
    Stack<Integer> stack = new Stack<>();
    int answer=0;
    for(char c: str.toCharArray()){
      if(Character.isDigit(c)){
        stack.push(Integer.parseInt(Character.toString(c)));
      }else{
        if(c=='*'){
          int i1=stack.pop();
          int i2=stack.pop();
          answer=i2*i1;
          stack.push(answer);
        }
        else if(c=='+'){
          int i1=stack.pop();
          int i2=stack.pop();
          answer=i2+i1;
          stack.push(answer);
        }
        else{
          int i1=stack.pop();
          int i2=stack.pop();
          answer=i2-i1;
          stack.push(answer);
        }
      }
    }
    return stack.pop();
  }
}
반응형