[Algorithm] 프로그래머스 > 두 정수 사이의 합
반응형
[Algorithm] 프로그래머스 > 두 정수 사이의 합

문제
두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.
https://programmers.co.kr/learn/courses/30/lessons/12912
제한 조건
- a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
- a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
- a와 b의 대소관계는 정해져있지 않습니다.
입출력 예
| a | b | return |
| 3 | 5 | 12 |
| 3 | 3 | 3 |
| 5 | 3 | 12 |
풀이
function solution(a, b) {
if(a === b) {
return a;
}
let result = 0;
let min = Math.min(a, b);
let max = Math.max(a, b);
for(min; min <= max; min++) {
if(min === 0) continue;
result += min;
}
return result;
}
타인 풀이
function solution(a, b) {
let result = (a < b) ? a : b;
while(a !== b) {
result += ++a;
}
return result;
}
정리
Math.min(), Math.max() 메소드
반응형
'프로그래밍 > Algorithm' 카테고리의 다른 글
| [Algorithm] 프로그래머스 > 이상한 문자 만들기 (3) | 2020.12.30 |
|---|---|
| [Algorithm] 프로그래머스 > 평균 구하기 (2) | 2020.12.29 |
| [Algorithm] 프로그래머스 > 핸드폰 번호 가리기 (1) | 2020.12.28 |
| [Algorithm] 프로그래머스 > 콜라츠 추측 (1) | 2020.12.27 |
| [Algorithm] 프로그래머스 > 같은 숫자는 싫어 (1) | 2020.12.13 |
댓글
이 글 공유하기
다른 글
-
[Algorithm] 프로그래머스 > 평균 구하기
[Algorithm] 프로그래머스 > 평균 구하기
2020.12.29 -
[Algorithm] 프로그래머스 > 핸드폰 번호 가리기
[Algorithm] 프로그래머스 > 핸드폰 번호 가리기
2020.12.28 -
[Algorithm] 프로그래머스 > 콜라츠 추측
[Algorithm] 프로그래머스 > 콜라츠 추측
2020.12.27 -
[Algorithm] 프로그래머스 > 같은 숫자는 싫어
[Algorithm] 프로그래머스 > 같은 숫자는 싫어
2020.12.13