프로그래머스 Lv.0 간단한 식 계산하기
![](https://t1.daumcdn.net/keditor/emoticon/face/large/073.png)
문자열 binomial이 매개변수로 주어진다.
binomial은 "a op b"형태의 이항식이고,
a와 v는 음이 아닌 정수, op는 사칙연산 중 하나이다.
주어진 식을 계산해서 return하라.
binomial | result |
"43 + 12" | 55 |
"0 - 7777" | -7777 |
"40000 * 40000" | 1600000000 |
** 풀이 방법
binomial의 공백을 없앤다.
binomial = binomial.replace(" ","");
StringTokenizer를 사용해서 사칙연산 기호 기준으로 나눈다.
각 사칙연산 기호에 맞는 a와 b의 연산을 해준다.
String func="";
StringTokenizer str = new StringTokenizer(binomial,"+-*/",true);
while(str.hasMoreTokens()) {
func = str.nextToken();
//func가 +일 때
if (func.equals("+")) {
func = str.nextToken();
result += Long.parseLong(func);
//func가 -일 때
} else if (func.equals("-")) {
func = str.nextToken();
result -= Long.parseLong(func);
//func가 *일 때
} else if (func.equals("*")) {
func = str.nextToken();
result *= Long.parseLong(func);
//func가 /일 때
} else if (func.equals("/")) {
func = str.nextToken();
result /= Long.parseLong(func);
//사칙연산 이외 정수!
} else {
result = Long.parseLong(func);
}
}
<> 전체 코드 </>
import java.util.*;
class Solution {
public long solution(String binomial) {
long result = 0;
binomial=binomial.replace(" ","");
String func="";
StringTokenizer str = new StringTokenizer(binomial,"+-*/",true);
while(str.hasMoreTokens()) {
func = str.nextToken();
if (func.equals("+")) {
func = str.nextToken();
result += Long.parseLong(func);
} else if (func.equals("-")) {
func = str.nextToken();
result -= Long.parseLong(func);
} else if (func.equals("*")) {
func = str.nextToken();
result *= Long.parseLong(func);
} else if (func.equals("/")) {
func = str.nextToken();
result /= Long.parseLong(func);
} else {
result = Long.parseLong(func);
}
}
return result;
}
}
반응형
'개발로그 > 알고리즘' 카테고리의 다른 글
프로그래머스 Lv.0 문자열 겹쳐쓰기 (0) | 2023.07.25 |
---|---|
프로그래머스 Lv.1 가장 가까운 같은 글자 (0) | 2023.07.25 |
프로그래머스 Lv.0 세로 읽기 (0) | 2023.07.24 |
프로그래머스 Lv.0 숨어있는 숫자의 덧셈 (2) (0) | 2023.07.24 |
프로그래머스 Lv.0 연속된 수의 합 (0) | 2023.07.24 |
댓글