C++ 문제 풀이/프로그래머스
[프로그래머스/C++] 없는 숫자 더하기
leejy811
2024. 1. 14. 17:25
1. 문제 설명
2. Solution
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<int> numbers) {
int answer = 0;
for(int i = 0;i < 10;i++) {
if(find(numbers.begin(), numbers.end(), i) == numbers.end())
answer += i;
}
return answer;
}
본 문제는 0~9까지의 숫자 중 일부가 들어있는 정수 배열에서 없는 수를 모두 더한 수를 return 하는 것인데 본인은 find 함수를 통해서 for문에서 i 숫자를 가지고 있지 않은 수를 더해주었다. 하지만 다른 사람들의 풀이를 보다가 굉장히 신기한 풀이를 발견하였는데
#include <bits/stdc++.h>
using namespace std;
int solution(vector<int> numbers) {
return 45 - accumulate(numbers.begin(), numbers.end(), 0);
}
문제에서 0~9라고 범위가 주어진 점과 없는 숫자 자체를 반환하는 것이 아닌 합을 반환하는 것 이므로 만대로 빼는 것도 가능하다는 것을 깨달았다. 그리고 배열의 합을 반환하는 accumulate라는 함수가 있다는 것도 알게되었다.