Level1
문제
문제 설명
두 정수 a, b가 주어졌을 때 a와 b 사이에 속한 모든 정수의 합을 리턴하는 함수, solution을 완성하세요.
예를 들어 a = 3, b = 5인 경우, 3 + 4 + 5 = 12이므로 12를 리턴합니다.
- a와 b가 같은 경우는 둘 중 아무 수나 리턴하세요.
- a와 b는 -10,000,000 이상 10,000,000 이하인 정수입니다.
- a와 b의 대소관계는 정해져있지 않습니다.
a | b | return |
3 | 5 | 12 |
3 | 3 | 3 |
5 | 3 | 12 |
풀이
사용언어 : C++
#include <string>
#include <vector>
#include <iostream>
using namespace std;
long long solution(int a, int b) {
long long answer = 0;
int front = a;
int back = b;
if ( a > b ){
front = b;
back = a;
}
for( int i = front ; i <= back; ++i){
answer += i;
}
return answer;
}
다른사람의 풀이
#include <string>
#include <vector>
using namespace std;
long long solution(int a, int b) {
return (long long)(a + b) * (abs(a - b) + 1) / 2;
}
// 시그마 공식
// 다른 풀이의 댓글을 보고 시그마 공식이라는걸 찾아보고 수업시간에 배웠던 기억을 되짚어 볼수 있었다.
#include <string>
#include <vector>
using namespace std;
long long solution(int a, int b) {
long long answer = 0;
if (a > b) a ^= b ^= a ^= b;
answer = (long long)b * -~b / 2 - (long long)a * ~-a / 2;
return answer;
}
// 비트연산자를이용
// 이전 회사에서 비트연산자를 이용해 저장했던 기억을 되짚어 볼수 있었다.
출처 : https://school.programmers.co.kr/learn/courses/30/lessons/12912
'개발 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/C++] 콜라츠 추측 (0) | 2022.11.13 |
---|---|
[프로그래머스/C++] 서울에서 김서방 찾기 (0) | 2022.11.12 |
[프로그래머스/C++] 나머지가 1이 되는 수 찾기 (0) | 2022.11.10 |
[프로그래머스/C++] 문자열 정수로 바꾸기 (0) | 2022.11.10 |
[프로그래머스/C++] 정수 내림차순으로 배치 (0) | 2022.11.09 |