-
[프로그래머스] 없는 숫자 더하기 c++Coding Test/programmers 2022. 8. 19. 13:39728x90
문제 설명
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'Coding Test > programmers' 카테고리의 다른 글
[프로그래머스] 성격 유형 검사하기 c++ (0) 2022.08.19 [프로그래머스] 소수 만들기 c++ (0) 2022.08.19 [프로그래머스] 크레인 인형뽑기 c++ (0) 2022.08.18 [프로그래머스] 키패드 누르기 c++ (0) 2022.08.18 [프로그래머스] 숫자 문자열과 영단어 c++ (1) 2022.08.18 - 1 ≤ numbers의 길이 ≤ 9