본문 바로가기

코딩 테스트/프로그래머스

[Level 1] 없는 숫자 더하기

728x90
반응형

제한사항으로 숫자가 정해져있어서 그냥 10칸 짜리 배열을 만들고 숫자가 있으면 해당하는 인덱스를 증가시키고 나중에 0인 인덱스만 구하는 방법으로 만들었다.

범위기반 for문을 사용했기 때문에 인덱스를 구할 때를 유의해야한다.

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int solution(vector<int> numbers) {
    int answer = 0;
    vector<int> arr(10);
    for(auto & n : numbers)
    {
        arr[n]++;
    }
    for(auto & n : arr)
    {
        if(n == 0)
            answer += &n - &*arr.begin();   // range based for에서 인덱스를 구하는 방법
    }

    return answer;
}

 

 

728x90
반응형