Coding Test/programmers
[프로그래머스] 없는 숫자 더하기 c++
owls
2022. 8. 19. 13:39
728x90
문제 설명
0부터 9까지의 숫자 중 일부가 들어있는 정수 배열 numbers가 매개변수로 주어집니다. numbers에서 찾을 수 없는 0부터 9까지의 숫자를 모두 찾아 더한 수를 return 하도록 solution 함수를 완성해주세요.
제한 사항
- 1 ≤ numbers의 길이 ≤ 9
- 0 ≤ numbers의 모든 원소 ≤ 9
- numbers의 모든 원소는 서로 다릅니다.
입출력 예
numbers | result |
[1,2,3,4,6,7,8,0] | 14 |
[5,8,4,0,6,7,9] | 6 |
풀이
0 ~ 9 까지의 합은 {n * (n+1) } / 2 공식을 사용해서 구할 수 있따.
0 ~ 9 까지의 합은 = 1 ~ 9 까지의 합과 같으므로 (9 * 10) / 2 = 45 이다.
accumulate 함수를 이용하여 numbers벡터 원소들의 합을 구한다.
(0 ~ 9 ) 의 합 , numbers의 합의 차를 구하면 된다.
#include <string>
#include <vector>
#include <numeric>
using namespace std;
int solution(vector<int> numbers) {
int answer = 0;
int asum = (9 * 10) / 2 ; //45
int nsum = accumulate(numbers.begin(), numbers.end() , 0);
answer = asum - nsum;
return answer;
}
728x90