Java/프로그래머스
[JAVA] 프로그래머스 - 문자열 계산하기
쥬크버그
2024. 5. 5. 14:19
https://school.programmers.co.kr/learn/courses/30/lessons/120902
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
정답
class Solution {
public int solution(String my_string) {
String arr[] = my_string.split(" "); //공백으로 구분
int answer = Integer.parseInt(arr[0]);
for(int i=0; i<arr.length; i++)
{
if(arr[i].equals("+"))
{
answer+=Integer.parseInt(arr[i+1]);
}
else if(arr[i].equals("-"))
{
answer-=Integer.parseInt(arr[i+1]);
}
}
return answer;
}
}
다른 사람의 풀이
import java.util.*;
class Solution {
public int solution(String my_string) {
int answer = 0;
StringTokenizer st = new StringTokenizer(my_string);
int length = st.countTokens();
Stack<Integer> stack = new Stack<Integer>();
while(st.hasMoreTokens()){
String str = st.nextToken();
if(stack.isEmpty()) {
stack.push(Integer.parseInt(str));
continue;
}
if(str.equals("+")){
stack.push(stack.pop()+Integer.parseInt(st.nextToken()));
}else if(str.equals("-")){
stack.push(stack.pop()-Integer.parseInt(st.nextToken()));
}
}
answer = stack.pop();
return answer;
}
}