CodeWars 코딩 문제 2021/02/09 - Evaluate a postfix expression

이호현·2021년 2월 9일
0

Algorithm

목록 보기
78/138

[문제]

Imagine you are in a universe where you can just perform the following arithematic operations. Addition(+), Subtraction(-), Multiplication(*), Division(/). You are given given a postfix expression. Postfix expression is where operands come after operator. Each operator and operand are seperated by a space. You need to evaluate the expression.

For example: 25 45 + is equivalent of 25 + 45, hence the answer would be 70. Instead if you are given 20 40 + 60 , it is equivalent of (20+40) 60, hence the answer should be 3600. 20 40 60 + is equivalent of 20 (40 + 60) = 2000.

Create a method 'evaluate' that takes a string as input and returns a long resulted in the evaluation. Just concentrate on happy paths. Assume that expression is always valid and division is always an integer division.

(요약) 주어진 문자열 수식을 풀어라. 숫자1 숫자2 연산기호 순으로 나오면 숫자1 연산기호 숫자2 이런 순으로 수식 계산해야됨.

[풀이]

function postfixEvaluator(string) {
  const reg = /[\+\-\*\/]/;

  const splitArr = string.split(' ');

  while(true) {
    if(splitArr.length === 1) break;

    const index = splitArr.findIndex((str) => (str.length === 1 && reg.test(str)));

    const tempNum = parseInt(eval(`${splitArr[index - 2]} ${splitArr[index]} ${splitArr[index - 1]}`));

    splitArr.splice(index - 2, 3, tempNum);
  }

  return splitArr[0];
}

사칙연산기호만 찾는 정규식을 만들고, 주어진 문자열을 빈칸으로 split.
split한 배열에서 사칙연산기호를 찾으면 앞에 숫자 두 개를 연산 시키고, 숫자 두개와 연산기호를 제거하고 그 자리에 방금 연산해서 나온 숫자를 넣음.
배열에 계산이 완료된 숫자 하나만 남을 때까지 반복.
마지막에 배열에 남은 요소는 당연히 숫자일테니 그것을 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글