저장을 습관화
프로그래머스 LV.0 간단한 식 계산하기 본문
프로그래머스 LV.0 간단한 식 계산하기
https://school.programmers.co.kr/learn/courses/30/lessons/181865
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 명
간단한 식 계산하기
2. 문제 설명
문자열 binomial이 매개변수로 주어집니다. binomial은 "a op b" 형태의 이항식이고 a와 b는 음이 아닌 정수, op는 '+', '-', '*' 중 하나입니다. 주어진 식을 계산한 정수를 return 하는 solution 함수를 작성해 주세요.
3. 제한 사항
- 0 ≤ a, b ≤ 40,000
- 0을 제외하고 a, b는 0으로 시작하지 않습니다.
4. 예시
binomial | result |
"43 + 12" | 55 |
"0 - 7777" | -7777 |
"40000 * 40000" | 1600000000 |
5. 기본 제공 코드
function solution(binomial) {
var answer = 0;
return answer;
}
6. 제출한 내 답
const solution = (binomial) => {
let a = +binomial.split(" ")[0];
let op = binomial.split(" ")[1];
let b = +binomial.split(" ")[2];
return op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : a / b;
};
6-2. VSC에 작성한 내용
const solution = (binomial) => {
let a = +binomial.split(" ")[0];
let op = binomial.split(" ")[1];
let b = +binomial.split(" ")[2];
return op === "+" ? a + b : op === "-" ? a - b : op === "*" ? a * b : a / b;
};
// 테스트
console.log(solution("43 + 12"));
console.log(solution("0 - 7777"));
console.log(solution("40000 * 40000"));
7. 특이사항
없음
8. 다른 사람이 작성한 답
8-1. 계산식 함수 미리 선언
const ops = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
};
function solution(binomial) {
const [a, op, b] = binomial.split(' ');
return ops[op](+a, +b);
}
8-2. 좀 더 깔끔한 변수 선언
function solution(binomial) {
const [a,ex,b] = binomial.split(" ");
return (ex === "+")? +a+ +b : (ex === "-")? a - b : a*b
}
'코딩 테스트 > 프로그래머스 - 자바스크립트' 카테고리의 다른 글
프로그래머스 LV.1 음양 더하기 (0) | 2023.09.18 |
---|---|
프로그래머스 LV.0 직각삼각형 출력하기 (0) | 2023.09.18 |
프로그래머스 LV.0 9로 나눈 나머지 (0) | 2023.09.18 |
프로그래머스 LV.0 약수 구하기 (0) | 2023.09.18 |
프로그래머스 LV.0 문자열 잘라서 정렬하기 (0) | 2023.09.17 |